15. 三数之和 - 力扣(LeetCode) (leetcode-cn.com)
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) { 4 vector<vector<int>> result; 5 sort(nums.begin(), nums.end()); 6 7 // 找出a + b + c = 0 a = nums[i], b = nums[left], c = nums[right] 8 for (int i = 0; i < nums.size(); i++) { //去重原则,先判断了,利用了条件,再下一位碰到同样元素时去重 9 // 对a去重 10 if(i > 0 && nums[i] == nums[i - 1]) { 11 continue; 12 } 13 int left = i + 1; 14 int right = nums.size() - 1; 15 while (right > left) { 16 17 if (nums[i] + nums[left] + nums[right] > 0) { 18 right--; 19 } else if (nums[i] + nums[left] + nums[right] < 0) { 20 left++; 21 } else if (nums[i] + nums[left] + nums[right] == 0){ 22 result.push_back(vector<int>{nums[i], nums[left], nums[right]}); 23 right--; 24 left++; 25 while (right > left && nums[right] == nums[right + 1]) right--;//对b去重 26 while (right > left && nums[left] == nums[left - 1]) left++;//对c去重 27 } 28 } 29 30 } 31 return result; 32 } 33 };View Code