1,题目要求
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]
]
给定n个整数的数组nums,是否有元素a,b,c在nums中,a + b + c = 0? 找到数组中所有唯一的三元组,它们的总和为零。
2,题目思路
对于这道题,是找到一个数组中所有的三元组,使得加和为0。
之前有一道题目,也是类似的题目,只不过是两个数字的加和:
Two Sun
在那道题目中,我们使用target - nums[I]
来避免穷举,并利用unordered_map
来避免重复。
在这道题目中,总的想法是类似的,不过此时我们必须要一定的搜索。
当我们对nums进行sort之后,令target = -nums[i]
,然后在i+1
到nums.size()-1
之间寻找两个数字之和等于target
即可。
为了避免重复,基于sort的特性,重复的数字一定是挨在一起的,因此,在找到目标后,直接跳过它们即可。
3,代码实现
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for(int i = 0;i<nums.size();i++){
int currTarget = -nums[i];
int front = i+1;
int back = nums.size()-1;
while(front < back){
int sum = nums[front] + nums[back];
//寻找sum == res的front和back
if(sum < currTarget)
front++;
else if(sum > currTarget)
back--;
else{
//找到了对应的sum
vector<int> tmp {nums[front], nums[i], nums[back]};
res.push_back(tmp);
front++, back--;
//将连续的重复的数字进行跳过,否则会有重复的结果
while(front < back && nums[front] == nums[front-1])
front++;
while(front < back && nums[back] == nums[back+1])
back--;
}
}
while(i+1 < nums.size() && nums[i+1] == nums[i])
i++;
}
return res;
}
};