Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
先是比较笨的方法,需要注意查重,注意标志位的移动
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int>> ans;
sort(num.begin(),num.end());
int i=0,j,k;
int n=num.size();
if(n<3) return ans;
while(i<n){
j=i+1;
k=n-1;
if(num[i]>0){
break;
}
int temp=0-num[i];
while(j<k){
if(num[j]+num[k]==temp){
vector<int> temp1;
temp1.push_back(num[i]);
temp1.push_back(num[j]);
temp1.push_back(num[k]);
ans.push_back(temp1);
j++;
while(j<k&&num[j]==num[j-1])
j++;
k--;
while(j<k&&num[k]==num[k+1])
k--;
}else if(num[j]+num[k]<temp){
j++;
while(j<k&&num[j]==num[j-1])
j++;
}else{
k--;
while(j<k&&num[k]==num[k+1])
k--;
}
}
i++;
while(i<n&&num[i]==num[i-1])
i++;
}
return ans;
}
};