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)
public class Solution { public List<List<Integer>> threeSum(int[] num) { List<List<Integer> > result = new ArrayList<List<Integer> >(); Arrays.sort(num); int length = num.length; if(length >= 3) { for(int i = 0; i < length - 2 && num[i] <= 0; ++i) { int start = i + 1, end = length - 1; //find all solution starting with num[i] while(start < end){ int sum = num[i] + num[start] + num[end]; if(sum < 0) //num[start] is too small ++start; else if(sum > 0) //num[end] is too large --end; else { //find a solution List<Integer> oneSolution = new ArrayList<Integer>(); oneSolution.add(num[i]); oneSolution.add(num[start]); oneSolution.add(num[end]); result.add(oneSolution); //remove the duplicates do{ ++start; }while(start < end && num[start - 1] == num[start]); do{ --end; }while(start < end && num[end] == num[end + 1]); } } //remove the duplicates of num[i] since we have found all solutions //staring with num[i]. while(i + 1 < length - 2 && num[i] == num[i + 1]) ++i; } } return result; } }