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)
1 public class Solution { 2 public List<List<Integer>> threeSum(int[] num) { 3 HashSet<List<Integer>> set = new HashSet<List<Integer>>(); 4 int len=num.length; 5 Arrays.sort(num); 6 for (int i = 0; i < len-2; i++) { 7 if (num[i]>0)break; 8 for (int j = len-1 ; j >i+1 ; j--) { 9 if (num[j]<0) break; 10 int ab = num[i] + num[j]; 11 int c = -ab; 12 int k = bs(c, num, i + 1, j - 1); 13 if (k>0) { 14 ArrayList<Integer> list = new ArrayList<Integer>(); 15 list.add(num[i]); 16 list.add(num[k]); 17 list.add(num[j]); 18 set.add(list); 19 } 20 } 21 } 22 return new ArrayList<List<Integer>>(set); 23 } 24 int bs(int c, int[] num, int l, int r) { 25 if(num[l] > c || num[r] < c) return -1; 26 while(l <= r) { 27 int m = (l+r)/2; 28 if(num[m] == c) return m; 29 else if(num[m] < c) l = m+1; 30 else r = m-1; 31 } 32 return -1; 33 } 34 }