class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> ans;
int n = nums.size();
if(n < 4) {
return ans;
}//如果大小小于4,就可以直接返回了
sort(nums.begin(), nums.end());
for(int i = 0; i < n - 3; i++) {
if(i > 0 && nums[i] == nums[i - 1]) {
continue;
}
if( nums[i] + nums[i + 1] > target - nums[i + 2] - nums[i + 3] ) {
break;
//这里这么写是为了不溢出,四个数相加会可能会溢出
}
if( nums[i] + nums[n - 1] < target - nums[n - 2] - nums[n - 3] ) {
continue;
}
for(int j = i + 1; j < n - 2; j++) {
if(j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
if(nums[i] + nums[j] > target - nums[j + 1] - nums[j + 2]) {
break;
}
if(nums[i] + nums[j] < target - nums[n - 1] - nums[n - 2]) {
continue;
}
int left = j + 1, right = n - 1;
while(left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if(sum == target) {
ans.push_back({nums[i], nums[j], nums[left], nums[right]});
while( (left < right) && (nums[left] == nums[left + 1]) ){
left++;
}
left++;
while( (left < right) && (nums[right] == nums[right - 1]) ){
right--;
}
right--;
}
else if(sum < target) {
left++;
}
else {
right--;
}
}
}
}
return ans;
}
};
06-26
3324
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-18
421
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-16
278
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-16
320
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
199
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
659
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)