题目
代码
public class Solution {
/**
* @param numbers: Give an array
* @param target: An integer
* @return: Find all unique quadruplets in the array which gives the sum of zero
*/
public List<List<Integer>> fourSum(int[] numbers, int target) {
// write your code here
List<List<Integer>> lists = new LinkedList<>();
if(numbers==null){
return lists;
}
Arrays.sort(numbers);
for(int i=0;i<numbers.length;i++){
if(i>0&&numbers[i]==numbers[i-1]){
continue;
}
for(int j=i+1;j<numbers.length;j++){
if(j>i+1&&numbers[j]==numbers[j-1]){
continue;
}
for(int m=j+1,n=numbers.length-1;m<n;){
if (m>j+1 && numbers[m-1]==numbers[m]){
++m; // duplication
continue;
}
if (n<numbers.length-1&& numbers[n]==numbers[n+1]){
--n; // duplication
continue;
}
int sum=numbers[i]+numbers[j]+numbers[m]+numbers[n];
if(sum>target){
n--;
}else if(sum<target){
m++;
}else {
List<Integer> temp=new LinkedList<>();
temp.add(numbers[i]);temp.add(numbers[j]);temp.add(numbers[m]);temp.add(numbers[n]);
m++;
lists.add(temp);
}
}
}
}
return lists;
}
}