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.
先用了个2sum变种过来的方法,三个里面拿掉一个做target,另外两个做2sum...可惜。。。没通过时间测试。。。。感觉是O(N^2)的算法。。。看了下leetcode discussion,好像好多人没通过。。。
</pre><pre name="code" class="cpp">class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
set<vector<int>> mySet;
sort(num.begin(),num.end());
for (int i=0; i<num.size();i++)
twoSum(num,mySet,i);
vector<vector<int>> ct(mySet.begin(),mySet.end());
return ct;
}
void twoSum(vector<int> &num, set<vector<int>>& ct, int ind)
{
int beg=0;
int end=num.size()-1;
int target=num[ind];
int val=-1*target;
while(beg<end){
if (beg==ind)
beg++;
if (end==ind)
end--;
int sum=num[beg]+num[end];
vector<int> s;
if (sum==target){
if (val<num[beg])
s={val,num[beg],num[end]};
else if (val>num[end])
s={num[beg],num[end],val};
else
s={num[beg],val,num[end]};
ct.insert(s);
beg++;
}
if (sum<target)
beg++;
else
end--;
}
}
};
看来照抄2sum是不行的。。。。不偷懒的话就得从头写, 基本上两个优化:一个是如果排序后这个数和之前的数一样,那就continue,这个也是解决output limit的问题。第二个就是双指针循环的时候如果一样跳过。 test还是过了。。。据说有hash map的办法,改天再看
class Solution {
public:
vector< vector<int> > threeSum(vector<int> &num) {
vector< vector<int> > ct;
sort(num.begin(),num.end());
int size=num.size();
if (size<3)
return ct;
for (int i=0; i<size-2;i++){
if (i>0 && num[i]==num[i-1])
continue;
int val=num[i];
int beg=i+1;
int end=size-1;
while(beg<end){
int sum=val+num[beg]+num[end];
if (sum==0){
vector<int> tmp={val,num[beg],num[end]};
ct.push_back(tmp);
beg++;
end--;
while (beg<size-2 && num[beg] == num[beg-1])
beg++;
while (end>0 && num[end]==num[end+1])
end--;
} else if (sum<0) {
beg++;
} else{
end--;
}
}
}
return ct;
}
};