Question:
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: The solution set must not contain duplicate triplets.
上一篇的这道题的解答有点问题,结果中出现了冗余,本来想在上篇的代码的基础上做出改进,直接写出去掉冗余结果的代码,但是没 试成功,网上看了看别人对这道题的思路,有一点点启发,根据所给的例子,我的思路如下图:
Answer:
class Solution {
public:
vector<vector<int> >*r;
vector<vector<int>> threeSum(vector<int>& nums) {
r= new vector<vector<int>>();
sort(nums.begin(), nums.end());
for(int i = 0; i<nums.size(); i++)
{
//跳过相同的i
while(i>0 && i<nums.size ()&& nums[i] == nums[i-1])
i++;
int j = i + 1;
int p = nums.size()- 1;
while(j < p)
{
if(nums[i] + nums[j] + nums[p] == 0)
{
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(nums[p]);
r->push_back(tmp);
j ++;
p --;
//跳过相同的j
while(j < p && nums[j] == nums[j-1])
j ++;
//跳过相同的p
while(p> j && nums[p] == nums[p+1])
p --;
}
else if(nums[i] + nums[j] + nums[p] < 0)
{
j ++;
//跳过相同的j
while(j < p && nums[j] == nums[j-1])
j ++;
}
else
{
p --;
//跳过相同的p
while(p > j && nums[p] == nums[p+1])
p --;
}
}
}
return *r;
}
};
Run Code Result:
Your input
[-1,0,1,2,-1,-4]
Your answer
[[-1,-1,2],[-1,0,1]]
Expected answer
[[-1,-1,2],[-1,0,1]]