# 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]
]

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


07-16 55

03-21 9

05-19 586

02-28 52

06-08 51

03-04 166

05-30 1411

08-31 945

05-30 79

03-20 17

09-18 1162

10-05 601

05-22 474

10-29 243

11-21 65

09-26 15

06-04 1262

03-19 83万+

04-14 62万+

03-13 16万+

#### 程序员请照顾好自己，周末病魔差点一套带走我。

©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客