排序,第一个数定,后面两个数参照两数之和
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
sort(num.begin(),num.end());
vector<vector<int>>ans;
if(num.size()<3)return ans;
for(int i=0;i<num.size()-2;i++)
{
if(i&&num[i]==num[i-1])continue;
int j=i+1,k=num.size()-1;
while(j<k)
{
int tempsum=num[i]+num[j]+num[k];
if(tempsum>0)
{
k--;
while(k<num.size()-1&&num[k]==num[k+1]&&j<k)k--;
}
else if(tempsum<0)
{
j++;
while(j&&j<k&&num[j]==num[j-1])j++;
}
else {
ans.push_back(vector<int>{num[i],num[j],num[k]});
j++,k--;
while(i<j&&num[j]==num[j-1]&&num[k]==num[k+1])j++,k--;
}
}
}
return ans;
}
};