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)
Analysis: Just use two pointers, the basic idea is the same as Two Sum. The time complexity is O(N2).
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
Arrays.sort(num); // sort the original array in ascending order
for(int i=0; i<=num.length-3; i++) {
if(i>0 && num[i]==num[i-1]) continue; // avoid duplicate, [0, 0, 0, 0]
int twoSum=0-num[i], low=i+1, high=num.length-1;
while(low < high) {
if(num[low]+num[high]<twoSum) low++;
else if(num[low]+num[high]>twoSum) high--;
else if(num[low]+num[high] == twoSum) {
ArrayList<Integer> tem = new ArrayList<Integer>();
tem.add(num[i]);
tem.add(num[low]);
tem.add(num[high]);
res.add(tem);
low++;
high--;
while(low<high && num[low]==num[low-1]) low++; // avoid duplicate
while(low<high && num[high]==num[high+1]) high--; // avoid duplicate
}
}
}
return res;
}
}