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)
题解
题意和two sum类似。方法也是那三种,a遍历3遍;b排序再夹逼;c遍历先取一个元素,剩下两个用two sum的标记法。
注意要采取去重措施。
这里我用的是方法b,先排序,再夹逼。
//cpp
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int> > res;
if(nums.size()<3)
return res;
sort(nums.begin(),nums.end());
auto tail=nums.end();
int target=0;
for(auto first=nums.begin();first<nums.end()-2;first++)
{
if(*first==*(first-1)&&first!=nums.begin())
continue;
auto second=first+1;
auto third=tail-1;
while(second<third)
{
if(*first+*second+*third<target)
second++;
else if(*first+*second+*third>target)
third--;
else
{
res.push_back({*first,*second,*third});
second++;
third--;
}
}
}
sort(res.begin(),res.end());
res.erase(unique(res.begin(),res.end()),res.end());
return res;
}
};