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;
}
}