mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 18. 4Sum.md
This commit is contained in:
parent
dc5539c3f7
commit
a88f6e6713
46
18. 4Sum.md
Normal file
46
18. 4Sum.md
Normal file
@ -0,0 +1,46 @@
|
||||
# [18. 4Sum](https://leetcode.com/problems/4sum/)
|
||||
# 思路
|
||||
和[3sum](https://github.com/ShusenTang/LeetCode/blob/master/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;
|
||||
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user