Given an arraySofnintegers, are there elementsa,b,cinSsuch thata+b+c= 0? Find all unique triplets in the array which gives the sum of zero.
Note: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]
]
这是2 sum的延伸,还是用2 pointer来解决。O(n^2)
publicArrayList<ArrayList<Integer>>threeSum(int[] numbers) {if (numbers ==null||numbers.length==0||numbers.length<3){returnnull; }Arrays.sort(numbers);// sort 1stArrayList<ArrayList<Integer>> result =newArrayList<>();int len =numbers.length;// remmeber to end when we were at the 3rd last element // n sum - 1, 3 sum so, 2for(int i =0; i< len -2;i++){ //skip duplicate hereif(i!=0&& numbers[i] == numbers[i-1]){continue; }int cur = numbers[i];int left = i+1;int right = len -1;while(left < right){int sum = cur + numbers[left] + numbers[right];if(sum ==0 ){ArrayList<Integer> temp =newArrayList<Integer>();temp.add(cur);temp.add(numbers[left]);temp.add(numbers[right]); left++; right--;//and herewhile(left<right&&numbers[left] == numbers[left-1]){ left++; }//and herewhile(left<right&&numbers[right] == numbers[right+1]){ right--; }result.add(temp); } elseif(sum >0){ right--; }else{ left++; } } }return result;}