mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
1.9 KiB
1.9 KiB
18. 4Sum
思路
和3sum这题基本一样的,注意这题由于循环层数比较多所以如果能
在外层循环判断一下的话可以提前终止循环或跳过某次循环,见代码。
时间复杂度O(n^3)
C++
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>>res;
int len = nums.size(), low, high, sum;
if(len < 4) return res;
sort(nums.begin(), nums.end());
for(int i = 0; i < len - 3; i++){
if(i != 0 && nums[i] == nums[i - 1]) continue;
// 提前退出或跳过不可能的情况
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target) break; // 最小的都比target大了,可以提前终止循环
if(nums[i]+nums[len-3]+nums[len-2]+nums[len-1] < target) continue;
for(int j = i + 1; j < len - 2; j++){
if(j != i + 1 && nums[j] == nums[j - 1]) continue;
low = j + 1;
high = len - 1;
while(low < high){
sum = nums[i] + nums[j] + nums[low] + nums[high];
if(sum < target)
while(++low < high && nums[low] == nums[low - 1]) ; // 不断右移low指针
else if(sum > target)
while(low < --high && nums[high] == nums[high + 1]) ; // 不断左移high指针
else{
vector<int>tmp = {nums[i], nums[j], nums[low++], nums[high--]};
res.push_back(tmp);
while(low < high && nums[low] == nums[low - 1]) low++;
while(low < high && nums[high] == nums[high + 1]) high--;
}
}
}
}
return res;
}
};