这题目和两个数的和求法一样,多了一层遍历,所以复杂度为O(n^2)
重要的地方是防止重复vector的push,所以要检测是否重复
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ret;
if(nums.empty())
return ret;
sort(nums.begin(),nums.end());
for(int i=0;i<=nums.size()-3;i++)
{
if(nums[i]>0)
break;
int start=i+1;
int last=nums.size()-1;
while(start<last)
{
if(nums[start]+nums[last]==-nums[i])
{
ret.push_back({nums[i],nums[start],nums[last]});
start++;
last--;
//ignore the duplicate
while(start<last&&nums[start]==nums[start-1])
start++;
while(start<last&&nums[last]==nums[last+1])
last--;
}
else if(nums[start]+nums[last]<-nums[i])
start++;
else
last--;
}
//ignore the duplicate
while(nums[i+1]==nums[i])
i++;
}
return ret;
}
int main()
{
vector<int> vec={-2,0,1,1,2};
auto ret=threeSum(vec);
for(auto vec:ret)
{
for(auto val:vec)
cout<<val<<" ";
cout<<endl;
}
return 0;
}