LeetCode/solutions/18. 4Sum.md
2020-06-17 09:23:52 +08:00

47 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [18. 4Sum](https://leetcode.com/problems/4sum/)
# 思路
和[3sum](./15.%203Sum.md)这题基本一样的,注意这题由于循环层数比较多所以如果能
在外层循环判断一下的话可以提前终止循环或跳过某次循环,见代码。
时间复杂度O(n^3)
# C++
``` 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;
}
};
```