leetcode-15-数组题-三数之和 发表于 2020-03-04 | 分类于 数据结构与算法 题目 解法12345678910111213141516171819202122232425262728293031323334353637383940414243class Solution {public: void changePosAdd(int &pos, vector<int>& nums, int n){ while((pos + 1 < n) && (nums[pos + 1] == nums[pos])) ++pos; ++pos; } void changePosSub(int &pos, vector<int>& nums){ while((pos - 1 > 0) && (nums[pos - 1] == nums[pos])) --pos; --pos; } vector<vector<int>> threeSum(vector<int>& nums) { int n = nums.size(); sort(nums.begin(), nums.end()); // 排序 vector<vector<int>> results; int now = 0; while(now < n-2){ int low = now + 1; int high = n - 1; while(low < high){ if(nums[low] + nums[high] == -nums[now]){ vector<int> res{nums[now], nums[low], nums[high]}; results.push_back(res); changePosAdd(low, nums, n); changePosSub(high, nums); }else if(nums[low] + nums[high] > -nums[now]){ changePosSub(high, nums); }else{ changePosAdd(low, nums, n); } } changePosAdd(now, nums, n); } return results; }}