Given an array nums
of n integers, are there elements a, b, c in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
题解:当在遍历的过程中, 发现满足解的元素重复的时候就跳过。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
int length = nums.size();
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < length; ++i)
{
int front = i + 1; int back = length - 1;
int target = -nums[i];
while (front < back)
{
int sum = nums[front] + nums[back];
if (sum < target)
{
++front;
}
else if (sum > target)
{
--back;
}
else
{
vector<int> ans(3, 0);
ans[0] = nums[i];
ans[1] = nums[front];
ans[2] = nums[back];
res.push_back(ans);
while ( front < back && nums[front] == ans[1])
{
++front;
}
while ( front < back && nums[back] == ans[2])
{
--back;
}
}
}
while (i + 1 < length && nums[i + 1] == nums[i])
++i;
}
return res;
}
};
当利用2Sum的时候,用
sort(res.begin(), res.end());
res.erase(unique(res.begin(), res.end()), res.end());
来剔除重复的元素。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
int length = nums.size();
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < length; ++i)
{
int target = 0 - nums[i];
TwoSum(res, nums, target, i, length);
}
sort(res.begin(), res.end());
res.erase(unique(res.begin(), res.end()), res.end());
return res;
}
void TwoSum(vector<vector<int>>& res, vector<int>& nums, int target, int start, int length)
{
unordered_set<int> hash;
for (int i = start + 1; i < length; ++i)
{
vector<int> ans;
int findNumber = target - nums[i];
if (hash.count(findNumber))
{
ans.push_back(nums[start]);
ans.push_back(findNumber);
ans.push_back(nums[i]);
res.push_back(ans);
continue;
}
else
hash.insert(nums[i]);
}
}
};
注意2Sum解在元素全为0的时候超时。