18. 4Sum
这题和15题算法基本一模一样
code
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
if(nums.size()<4)
return res;
for(int i=0;i<nums.size()-3;++i){
for(int j=i+1;j<nums.size()-2;++j){
int sum=target-nums[i]-nums[j];
int left=j+1,right=nums.size()-1;
while(left<right){
if(nums[left]+nums[right]==sum){
//cout<<left<<' '<<right<<';';
res.push_back({nums[i],nums[j],nums[left],nums[right]});
while(nums[left+1]==nums[left])
left++;
while(nums[right-1]==nums[right])
right--;
}
if(nums[left]+nums[right]>sum)
right--;
else
left++;
//cout<<left<<' '<<right<<';';
}
while(j<nums.size()-2&&nums[j+1]==nums[j])
j++;
}
while(i<nums.size()-3&&nums[i+1]==nums[i])
i++;
}
return res;
}
};
Last updated