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.
Note: The solution set must not contain duplicate quadruplets.
For 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]
]
Solution:
因为要去重,所以用TwoPointers instead of hashmap
思路:排序后,�for every element, and then for every the other element, use two pointers to find other two, with skipping process
Time Complexity: O(N) Space Complexity: O(N)
Note:如果是返回位置index的话,排序+two pointers 位置改变了 还需要原序列上找 index,不如用hashmap
Solution Code:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0) return result;
Arrays.sort(nums);
if (4 * nums[0] > target || 4 * nums[nums.length - 1] < target) // early not found
return result;
for(int i = 0; i < nums.length - 3; i++) {
if(i != 0 && nums[i] == nums[i - 1]) continue; //skip num1 dup
for(int j = i + 1; j < nums.length - 2; j++) {
if((j != i + 1) && nums[j] == nums[j - 1]) continue; //skip num2 dup
int target2sum = target - nums[i] - nums[j];
// two pointers
int start = j + 1, end = nums.length - 1;
while(start < end) {
if(nums[start] + nums[end] == target2sum) {
result.add(Arrays.asList(nums[i], nums[j], nums[start], nums[end]));
while(start < end && nums[start] == nums[start + 1]) start++; // skip num3 dup
while(start < end && nums[end] == nums[end - 1]) end--; // skip num4 dup
start++;
end--;
}
else if(nums[start] + nums[end] < target2sum) {
start++;
}
else {
end--;
}
}
}
}
return result;
}
}