给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路
双指针+排序,双指针使用条件一般是有序数组,先对数组进行排序后,循环枚举数组的每一个元素,固定该元素Ai,然后使用双指针在该元素右边寻找两数相加等于-Ai即可。
为了避免重复枚举,当前枚举元素与前一元素相同时,直接跳过。
代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<vector<int>> ans;
for(int first = 0; first < n; first++) {
if(first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int third = n - 1;
int target = -nums[first];
//双指针判断两数和等于-num[first]
for(int second = first + 1; second < n; second++) {
if(second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
while(second < third && (nums[second] + nums[third]) > target) {
third--;
}
if(second == third) {
break;
}
if(nums[second] + nums[third] == target) {
vector<int> tmp = {nums[first], nums[second], nums[third]};
ans.push_back(tmp);
}
}
}
return ans;
}
};