当前位置: 代码迷 >> 综合 >> leetcode 15. 3Sum (medium)
  详细解决方案

leetcode 15. 3Sum (medium)

热度:7   发布时间:2024-01-05 00:35:38.0

先排序,再夹逼

class Solution
{public:vector<vector<int>> threeSum(vector<int> &nums){vector<vector<int>> res;if (nums.size() < 3){return res;}int target = 0;sort(nums.begin(), nums.end());auto last = nums.end();for (auto i = nums.begin(); i < last - 2; i++){if (i > nums.begin() && *i == *(i - 1))continue;auto j = i + 1;auto k = last - 1;while (j < k){if (*i + *j + *k == target){res.push_back({*i, *j, *k});++j;--k;while (*j == *(j - 1) && j < k)++j;while (*k == *(k + 1) && j < k)--k;}else if (*i + *j + *k < target){++j;while (*j == *(j - 1) && j < k)++j;}else{--k;while (*k == *(k + 1) && j < k)--k;}}}return res;}
};
  相关解决方案