class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int size = nums.size();
if(size<3)
return res;
sort(nums.begin(),nums.end());
for(int i=0;i<size-2;++i)
{
while(i>0 && nums[i]==nums[i-1]) ++i; //第一个指针跳过重复元素
int j = i+1;
int k = size-1;
while(j<k)
{
int sum = nums[i]+nums[j]+nums[k];
if(sum==0)
{
vector<int> cur(3);
cur[0] = nums[i];
cur[1] = nums[j];
cur[2]= nums[k];
res.push_back(cur);
++j;
--k;
while(j<k && nums[j]==nums[j-1]) ++j; //如果和之前的元素相同就跳过
while(j<k && nums[k]==nums[k+1]) --k;
}
else if(sum<0)
{
++j;
while(j<k && nums[j]==nums[j-1]) ++j; //第二个指针跳过重复元素
}
else
{
--k;
while(j<k && nums[k]==nums[k+1]) --k; //第三个指针跳过重复元素
}
}
}
return res;
}
};
转自
https://www.cnblogs.com/ganganloveu/p/3832180.html
参考
https://segmentfault.com/a/1190000008995599