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)
Subscribe to see which companies asked this question
分析:
采用与4sum相同的方法,两边同时往中间敢的方法,最好不要用map,会有INT_MAX,0等边界,
代码:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> v1;
map<int,int> m1;
if(nums.size()<3) return v1;
for(int i=0;i<nums.size();++i)
{
m1[nums[i]]++;
}
for(int i=0;i<(nums.size()-2);++i)
{
if(nums[i]>0) break;
if(i>0&&nums[i]==nums[i-1]) continue;
int t=i+1;
int k=nums.size()-1;
while(t<k)
{
if((nums[t]+nums[k]+nums[i])>0)--k;
else if((nums[t]+nums[k]+nums[i])<0)++t;
else
{
vector<int> v2{nums[i],nums[t],nums[k]};
v1.push_back(v2);
++t;--k;
while(t<k&&nums[t]==nums[t-1])++t;
while(t<k&&nums[k]==nums[k+1])++k;
}
}
}
return v1;
}
};