码迷,mamicode.com
首页 > 其他好文 > 详细

15 & 16. 3Sum & 3Sum Cloest

时间:2017-01-11 07:58:58      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:equal   code   span   get   pre   integer   loop   else   ica   

3Sum

Given a integer array, find all the unique 3-number pairs which sum = 0.

Solution O(N^2):

1. Sort the array, and makes this problem to a equal ‘2sum sorted‘ problem a1 + a2 = -a3(target)

2. from 0 to n-3,

        * cc1(if the nums[i] > 0, which means all the numbers following are larger than 0, break to end the loop)

 

        use two pointers from i+1 and n-1,

            if nums[lo] + nums[hi] > target, hi--;

            if nums[lo] + nums[hi] < target, lo++;

            if nums[lo] + nums[hi] == target, init an arraylist and add it into the list<list>

            *cc2(skip all the deplicate numbers)

 

3Sum Cloest (30lines)

Given a integer array and a number target, find the cloest sum of triplet to target. 

Similar solution as 3Sum, minimize the Math.abs( a1 + a1 + a3 - target )

Solution O(N^2):

1. Define variables ‘sum‘: the cloest value, ‘compare‘: the minimal difference

2. Sort the array,  

    when current difference < compare, update sum and compare

    there are three if as the problem above to control the ‘lo‘ and ‘hi‘

 

 1 public class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         Arrays.sort(nums);
 4         //length of the array
 5         int length = nums.length;
 6         //sum of three numbers
 7         int sum = target;
 8         //difference of target and sum
 9         int compare = Integer.MAX_VALUE;
10         //from begin to end, nums[i] is s1
11         for(int i = 0; i < length - 2; i++) {
12             int current = target - nums[i];
13             //two pointers, nums[lo] is s2, nums[hi] is s3
14             int lo = i + 1, hi = length - 1;
15             while(lo < hi) {
16                 //if s1 + s2 - current is smaller than compare, replace it
17                 int tmp = Math.abs(nums[lo] + nums[hi] -current);
18                 if(tmp < compare) {
19                     compare = tmp;
20                     sum = nums[lo] + nums[hi] + nums[i];
21                 }
22                 //if sum < target, lo++; if sum > target, hi--; if sum == target, end loop
23                 if(nums[lo] + nums[hi] + nums[i] < target) lo++;
24                 else if(nums[lo] + nums[hi] + nums[i] > target) hi--;
25                 else return sum;
26             }
27         }
28         return sum;
29     }
30 }

 

15 & 16. 3Sum & 3Sum Cloest

标签:equal   code   span   get   pre   integer   loop   else   ica   

原文地址:http://www.cnblogs.com/CornerCase/p/6272179.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!