题目:18. 四数之和
排序+双指针
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
vector<vector<int>> vec;
if(n < 4) return vec;
sort(nums.begin(), nums.end());
for(int a=0; a<n-3; a++)
{
if(a > 0 && nums[a] == nums[a-1]) continue;
if((long)nums[a] + nums[a+1] + nums[a+2] + nums[a+3] > (long)target) break;
if(nums[a] + nums[n-3] + nums[n-2] + nums[n-1] < target) continue;
for(int b=a+1; b<n-2; b++)
{
if(b > a+1 && nums[b] == nums[b-1]) continue;
if(nums[a] + nums[b] + nums[n-2] + nums[n-1] < target) continue;
int c = b+1, d = n-1;
while(c < d)
{
int ans = nums[a] + nums[b] + nums[c] + nums[d];
if(ans == target)
{
vec.push_back({nums[a], nums[b], nums[c], nums[d]});
c++;
d--;
while(c < d && nums[c] == nums[c-1]) c++;
while(c < d && nums[d] == nums[d+1]) d--;
}
else if(ans < target) c++;
else d--;
}
}
}
return vec;
}
};
|