18.4Sum 四數之和
18. 4Sum
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
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.
Example:
Given array nums = [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]
]
雙指針
和3Sum一樣,使用雙指針的方式進行搜搜。相當於再加多一重循環。在3Sum中,我們固定了一個值,然後剩餘的兩個指分別使用兩個指針遍歷。因此在4Sum中,我們同樣可以使用 相同的方法,固定兩個值,然後使用兩個指針進行遍歷。最後面得出結果。
在這裏使用了一個小技巧。就是在遍歷之前,我們先取了這次本次遍歷的最大值和最小值。如果目標值不在這個範圍內就直接跳過。
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length < 4) return result;
Arrays.sort(nums);
int len = nums.length;
for(int i = 0; i < len - 3; i++){
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target)
break;
if (nums[i] + nums[len - 1] + nums[len - 2] + nums[len - 3] < target)
continue;
for(int j = i + 1; j < len - 2 ; j++){
if( j > i + 1 && nums[j] == nums[j-1]){
continue;
}
int left = j + 1;
int right = len - 1;
if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target)
break;
if (nums[i] + nums[j] + nums[right - 1] + nums[right] < target)
continue;
while(left < right){
int ans = nums[i] + nums[j] + nums[left] + nums[right];
if(ans < target){
left ++;
} else if(ans > target){
right --;
} else {
result.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
left ++;
right --;
while(left < right && nums[left] == nums[left - 1]){
left ++;
}
while(left < right && nums[right] == nums[right + 1]){
right --;
}
}
}
}
}
return result;
}
}