leet code 18. 四数之和
作者:互联网
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;
}
};
标签:leet,四数,target,nums,int,18,++,right,left 来源: https://blog.csdn.net/qq_40253370/article/details/120818197