15 & 16. 3Sum & 3Sum Cloest

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了15 & 16. 3Sum & 3Sum Cloest相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 15. 3Sum

15. 3Sum

Leetcode 16. 3Sum Closest

15. 3Sum

15. 3Sum

leetcode 16 3Sum