题目
源码
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 List<List<Integer>> threeSum(int[] numbers) {
// write your code here
List<List<Integer>> result = new LinkedList<>();
if(numbers==null||numbers.length<3){
return result;
}
Arrays.sort(numbers);
for(int i=0;i<=numbers.length-3;){
int left=0-numbers[i];
int low=i+1;
int high=numbers.length-1;
while (low<high){
int temp=numbers[low]+numbers[high];
//System.out.printf("temp:%d,left:%d,low:%d,high:%d\n",temp,left,low,high);
if(temp==left){
List<Integer> l=new LinkedList<>();
l.add(numbers[i]);l.add(numbers[low]);l.add(numbers[high]);
//System.out.printf("%d,%d,%d\n",numbers[i],numbers[low],numbers[high]);
result.add(l);
int tempIndex=low;
while (low<high&&numbers[tempIndex]==numbers[low]){
low++;
}
}else if(temp>left){
high--;
}else {
low++;
}
}
int tempIndex=i;
while (i<=numbers.length-3&&numbers[tempIndex]==numbers[i]){
i++;
}
}
return result;
}
}