1 public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 if(num.length<3||num == null)
4 return res;
5
6 HashSet<ArrayList<Integer>> hs = new HashSet<ArrayList<Integer>>();
7
8 Arrays.sort(num);
9
10 for(int i = 0; i <= num.length-3; i++){
11 int low = i+1;
12 int high = num.length-1;
13 while(low<high){//since they cannot be the same one, low should not equal to high
14 int sum = num[i]+num[low]+num[high];
15 if(sum == 0){
16 ArrayList<Integer> unit = new ArrayList<Integer>();
17 unit.add(num[i]);
18 unit.add(num[low]);
19 unit.add(num[high]);
20
21 if(!hs.contains(unit)){
22 hs.add(unit);
23 res.add(unit);
24 }
25
26 low++;
27 high--;
28 }else if(sum > 0)
29 high --;
30 else
31 low ++;
32 }
33 }
34
35 return res;
36 }
1 public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 if(num.length<3||num == null)
4 return res;
5
6 Arrays.sort(num);
7
8 for(int i = 0; i <= num.length-3; i++){
9 if(i==0||num[i]!=num[i-1]){//remove dupicate
10 int low = i+1;
11 int high = num.length-1;
12 while(low<high){
13 int sum = num[i]+num[low]+num[high];
14 if(sum == 0){
15 ArrayList<Integer> unit = new ArrayList<Integer>();
16 unit.add(num[i]);
17 unit.add(num[low]);
18 unit.add(num[high]);
19
20 res.add(unit);
21
22 low++;
23 high--;
24
25 while(low<high&&num[low]==num[low-1])//remove dupicate
26 low++;
27 while(low<high&&num[high]==num[high+1])//remove dupicate
28 high--;
29
30 }else if(sum > 0)
31 high --;
32 else
33 low ++;
34 }
35 }
36 }
37 return res;
38 }