3Sum
Jan 18 '12
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)
//null, {},{1,2}, {-1,-1,1,0, -2, -1, 3}
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num==null || num.length<3) return res;
int sz=num.length;
Arrays.sort(num);
Set<ArrayList<Integer>> unique = new HashSet<ArrayList<Integer>>();
for(int i=0; i<sz-2 ;i++) {
int j=i+1;
int k=sz-1;
while(j<k) {
int x=num[i]+num[j]+num[k];
ArrayList<Integer> temp = new ArrayList<Integer>();
if(x==0) {
temp.add(num[i]);
temp.add(num[j]);
temp.add(num[k]);
if(!unique.contains(temp)) {
res.add(temp);
unique.add(temp);
}
++j;
--k; //may have duplication here
} else if(x<0){
++j;
} else {
--k;
}
}
}
return res;
}
}
}