给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
这个题主要的问题是会出现超时,和重复答案。
所以关键是想清楚:
1.为什么排序后,双指针是放在指定数字的右边,而不是一头一尾?这里就是为了去重,因为如果还是一头一尾,那么会出现重复答案
2. 在得到一组答案后,还需要做什么来去重?判断之后的数字和当前数字是否相等
3.还有个小细节,就是如果遍历的时候i>0或者前后相等时,continue
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
int len = nums.size();
vector<vector<int>> ans;
if(nums.empty()) return {};
for(int i = 0;i < len;++i){
if(i > 0 && nums[i] == nums[i-1]) continue; //去重
int newtar = -nums[i];//转换成两数之和的目标值
int low = i + 1;//去重
int high = len - 1;
while(low < high)
{
if(nums[low] + nums[high] == newtar)
{
ans.push_back({nums[i],nums[low],nums[high]});
while(low < high && nums[low] == nums[low + 1]) ++low; //去重
while(low < high && nums[high] == nums[high - 1]) --high;
low++;
--high;
}
else if(nums[low] + nums[high] < newtar) low++;
else high--;
}
}
return ans;
}
};