Wednesday, March 3, 2021, the weather is fine [Do not lament the past, do not waste the present, do not fear the future]
Contents of this article
1. Introduction
Leetcode 15. Sum of Three Numbers
2. Problem solution (sort + double pointer)
The main idea: sorting + double pointer , the difficulty is how to remove duplication .
The algorithm flow is as follows:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
const int n = nums.size();
for(int i=0;i<n;++i){
// 特判(剪枝)
if(nums[i]>0) return res;
// 如果第一个元素重复,提前退出
if(i>0 && nums[i]==nums[i-1]) continue;
int beg = i+1, end = n-1;
while(beg<end){
if(nums[beg]+nums[end]==-nums[i]){
// 保存符合条件的三元组
res.push_back({
nums[beg],nums[end],nums[i]});
// *重点:对第二个和第三个元素进行去重
while(beg<end && nums[beg]==nums[beg+1]) ++beg;
while(beg<end && nums[end]==nums[end-1]) --end;
++beg;
--end;
}
else if(nums[beg]+nums[end]>-nums[i])
--end;
else
++beg;
}
}
return res;
}
};
references
https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/