leetcode 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 的做法类似。在每层循环的开始可以进行一个判断,假如在此情况下的最小和都大于 target 则 break,若最大和都小于 target 则 continue
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int n=nums.size();
if(n<4)return res;
sort(nums.begin(), nums.end());
for(int i=0;i<n-3;i++){
if(i>0&&nums[i]==nums[i-1])continue;
int cur=nums[i];
if(cur+nums[i+1]+nums[i+2]+nums[i+3]>target)break;
if(cur+nums[n-1]+nums[n-2]+nums[n-3]<target)continue;
for(int j=i+1;j<n-2;j++){
if(j>i+1&&nums[j]==nums[j-1])continue;
cur=nums[i]+nums[j];
if(cur+nums[j+1]+nums[j+2]>target)break;
if(cur+nums[n-1]+nums[n-2]<target)continue;
int l=j+1,r=n-1;
while(l<r){
cur=nums[i]+nums[j]+nums[l];
if(cur+nums[l+1]>target)break;
if(cur+nums[n-1]<target){
while(l<r&&nums[l]==nums[l+1])l++;l++;
continue;
}
cur+=nums[r];
if(cur==target){
res.push_back(vector<int>{nums[i],nums[j],nums[l],nums[r]});
while(l<r&&nums[l]==nums[l+1])l++;l++;
}else if(cur>target){while(l<r&&nums[r]==nums[r-1])r--;r--;}
else {while(l<r&&nums[l]==nums[l+1])l++;l++;}
}
}
}
return res;
}
};