给你一个整数数组 nums
,判断是否存在三元组 [nums[i], nums[j], nums[k]]
满足 i != j
、i != k
且 j != k
,同时还满足 nums[i] + nums[j] + nums[k] == 0
。请
你返回所有和为 0
且不重复的三元组。
注意:答案中不可以包含重复的三元组。
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) { 4 vector<vector<int>> res; 5 sort(nums.begin(),nums.end()); 6 //对num采用三指针的方法 7 for (int i = 0; i < nums.size()-1; i++) 8 { 9 if (nums[i] > 0 ) break; 10 if (i > 1 && nums[i] == nums[i - 1]) continue; 11 int left = i + 1; 12 int right = nums.size() - 1; 13 while (left < right) 14 { 15 int sum = nums[i] + nums[left] + nums[right]; 16 if (sum < 0) left++; 17 if (sum > 0) right--; 18 if (sum == 0) 19 { 20 res.insert(res.end(), { nums[i] , nums[left] , nums[right] }); 21 while (right > left && nums[left] == nums[left + 1]) left++; 22 while (right > left && nums[right] == nums[right - 1]) right--; 23 left++; 24 right--; 25 } 26 } 27 } 28 return res; 29 } 30 }; 31 32 int main() { 33 vector<int> a = { -1,0,1,2,-1,-4 }; 34 vector<vector<int>> c; 35 Solution q; 36 c = q.threeSum(a); 37 for (const auto& p : c) 38 { 39 for (const auto& q : p) 40 { 41 printf("%d\n", q); 42 } 43 }}
标签:right,15,nums,int,三数,sum,vector,left From: https://www.cnblogs.com/lihaoxiang/p/17188317.html