[lintcode medium]3 sum
3Sum
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.
Example
For example, given array S = {-1 0 1 2 -1 -4}
, A solution set is:
(-1, 0, 1)
(-1, -1, 2)
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.
public class Solution { /** * @param numbers : Give an array numbers of n integer * @return : Find all unique triplets in the array which gives the sum of zero. */ public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) { // write your code here ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>(); if(numbers==null || numbers.length<3) { return result; } Arrays.sort(numbers); for(int i=0;i<numbers.length-2;i++) { if(i!=0 && numbers[i]==numbers[i-1]) { continue; } int left=i+1; int right=numbers.length-1; while(left<right) { int sum=numbers[left]+numbers[right]+numbers[i]; if(sum==0) { ArrayList<Integer> list=new ArrayList<Integer>(); list.add(numbers[i]); list.add(numbers[left]); list.add(numbers[right]); result.add(list); left++; right--; while(left<right && numbers[left]==numbers[left-1]) { left++; } while(left<right && numbers[right]==numbers[right+1]) { right--; } } else if(sum<0) { left++; } else { right--; } } } return result; } }