给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
双指针加去重
class Solution {public: vector> threeSum(vector & nums) { int len = nums.size(); sort(nums.begin(), nums.end()); map > check; vector > res; for(int i = 0; i < len - 2; i++) { int low = i + 1; int high = len - 1; while(low < high) { if(nums[low] + nums[high] == -nums[i]) { res.push_back({nums[i], nums[low], nums[high]}); //去重 while(nums[low] == nums[low + 1]) low++; low++; } if(nums[low] + nums[high] > -nums[i]) { high--; } else { low++; } } //去重 while(nums[i] == nums[i + 1]) i++; } return res; }};