3Sum

题目: 

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c). The solution set must not contain duplicate triplets.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:    (-1, 0, 1) (-1, -1, 2)

这题就是一个bianry search的变种。我们在固定一个元素后,相当于做一个two sum。有一个test case需要注意的是[0,0,0,0]。 所以我们需要略过这种重复多个元素的情况。

 1     public List<List<Integer>> threeSum(int[] num) {
 2         List<List<Integer>> res = new ArrayList<List<Integer>>();
 3         if (num == null || num.length == 0) {
 4             return res;
 5         }
 6         Arrays.sort(num);
 7         for (int i = 0; i < num.length - 2; i++) {
 8             while (i != 0 && i < num.length && num[i] == num[i - 1] ) {
 9                 i++;
10             }
11             /*   if (i != 0 && num[i] == num[i - 1]) {
12                 continue; // to skip duplicate numbers; e.g [0,0,0,0]
13             }
14 
15 */
16             int start = i + 1;
17             int end = num.length - 1;
18             while (start < end) {
19                 int val = num[i] + num[start] + num[end];
20                 if (val == 0) {
21                     ArrayList<Integer> subRes = new ArrayList<Integer>();
22                     subRes.add(num[i]);
23                     subRes.add(num[start]);
24                     subRes.add(num[end]);
25                     res.add(subRes);
26                     do{
27                         start++;
28                     }while (start < end && num[start] == num[start - 1]);
29                     do {
30                         end--;
31                     }while (start < end && num[end] == num[end + 1]);
32                 }else if (val < 0) {
33                     start++;
34                 }else if (val > 0) {
35                     end--;
36                 }
37                 
38             }
39         }
40         return res;
41     }
原文地址:https://www.cnblogs.com/gonuts/p/4414171.html