Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
Find all unique quadruplets in the array which gives the sum of target.
Example
Given array S = {1 0 -1 0 -2 2}
, and target = 0
. A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
public class Solution {
/**
* @param numbers : Give an array numbersbers of n integer
* @param target : you need to find four elements that's sum of target
* @return : Find all unique quadruplets in the array which gives the sum of
* zero.
*/
public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>> ();
Arrays.sort(numbers);
if(numbers.length < 3) return res;
for(int left = 0; left < numbers.length - 3; left ++) {
for(int G = left + 1; G < numbers.length - 2; G ++) {
int i = G + 1, j = numbers.length - 1;
while(i < j) {
if(numbers[left] + numbers[G] + numbers[i] + numbers[j] > target) j--;
else if(numbers[left] + numbers[G] + numbers[i] + numbers[j] < target) i++;
else {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(numbers[left]);
tmp.add(numbers[G]);
tmp.add(numbers[i]);
tmp.add(numbers[j]);
res.add(tmp);
while(j - 1 > i && numbers[j] == numbers[j - 1])
j--;
while(i + 1 < j && numbers[i] == numbers[i + 1])
i++;
i++;j--;
}
}
while(G + 1 < numbers.length - 2 && numbers[G] == numbers[G + 1]) G++;
}
while(left + 1 < numbers.length && numbers[left] == numbers[left + 1]) left++;
}
return res;
}
}
public class Solution {
/**
* @param numbers : Give an array numbersbers of n integer
* @param target : you need to find four elements that's sum of target
* @return : Find all unique quadruplets in the array which gives the sum of
* zero.
*/
public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>> ();
Arrays.sort(numbers);
if(numbers.length < 3) return res;
for(int left = 0; left < numbers.length; left ++) {
for(int right = numbers.length - 1; right > left + 2; right --) {
int i = left + 1, j = right - 1;
while(i < j) {
if(numbers[left] + numbers[right] + numbers[i] + numbers[j] > target) j--;
else if(numbers[left] + numbers[right] + numbers[i] + numbers[j] < target) i++;
else {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(numbers[left]);
tmp.add(numbers[i]);
tmp.add(numbers[j]);
tmp.add(numbers[right]);
res.add(tmp);
while(j - 1 > i && numbers[j] == numbers[j - 1])
j--;
while(i + 1 < j && numbers[i] == numbers[i + 1])
i++;
i++;j--;
}
}
while(right - 1 > left + 2 && numbers[right] == numbers[right - 1]) right--;
}
while(left + 1 < numbers.length && numbers[left] == numbers[left + 1]) left++;
}
return res;
}
}