3Sum
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)
先对数组进行排序,从头开始扫描,扫描的数作为固定的数。
a=num[i];
当固定了一个数以后,
选取b=num[i+1]=num[j]
选取c=num[n-1]=num[k]
若a+b+c=0
则找到了一个a,b,c,记录下来,j++,k--继续扫描
若a+b+c<0
则j++
若a+b+c>0
则k--
要注意去重的问题:
1.若num[i]=num[i-1],则跳过
2.若num[j]=num[j-1],则跳过
3.若num[k]=num[k+1],则跳过
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) { int n=num.size();
sort(num.begin(),num.end()); int i,j,k;
int a,b,c;
vector<vector<int> > result; for(i=;i<n-;i++)
{
j=i+;
k=n-; while(j<k)
{
a=num[i];
if(i>&&num[i]==num[i-])
{
break;
}
b=num[j];
if(j>i+&&num[j]==num[j-])
{
j++;
continue;
} c=num[k];
if(k<n-&&num[k]==num[k+])
{
k--;
continue;
} if(a+b+c==)
{
vector<int> tmp();
tmp[]=a;
tmp[]=b;
tmp[]=c;
result.push_back(tmp);
j++;
k--;
}
else if(a+b+c<)
{
j++;
}
else if(a+b+c>)
{
k--;
}
}
} return result; }
};