LeetCode/solutions/15. 3Sum.md

43 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.

# [15. 3Sum](https://leetcode.com/problems/3sum/)
# 思路
找出数组中的所有和为0的三个数组合。
先想一下如何求所有和为0的两个数的组合。可以这样考虑先将数组从小到大排序再设置两个指针low和high分别初始为数组两端计算两个指针的和sum
根据sum与0的大小关系适当调整指针:
* 若sum > 0说明和有点大了应该小一点则应该将high左移
* 若sum < 0说明和有点小了应该大一点则应该将low右移
* 若sum = 0说明刚刚好记录即可然后同时将low和high向中间移。
三个数的话其实思路是一致的只是外面多一层循环而已先将数组排序外层循环就是将当前位置的数定为第一个数然后就进入内层循环进行类似两个数的和的操作
注意跳过重复元素
时间复杂度O(n^2)空间复杂度O(1)
# C++
``` C++
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>>res;
int len = nums.size();
sort(nums.begin(), nums.end());
for(int i = 0; i < len - 2; i++){ // nums[i] 为三个数的第一个数
if(i > 0 && nums[i] == nums[i - 1]) continue;
int low = i + 1, high = nums.size() - 1;
while(low < high){
int sum = nums[i] + nums[low] + nums[high];
if(sum < 0)
while(++low < high && nums[low] == nums[low - 1]) ; // 不断右移low指针
else if(sum > 0)
while(low < --high && nums[high] == nums[high + 1]) ; // 不断左移high指针
else{
res.push_back(vector<int>{nums[i], nums[low], nums[high]});
while(nums[++low] == nums[low - 1]) ;
while(nums[--high] == nums[high + 1]) ;
}
}
}
return res;
}
};
```