标签:3sum vector begin style leetcode for while http info
先排序,然后固定一个值,使用双指针计算结果。
时间复杂度O(n^2),空间复杂度O(1)
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int> > res; int length = nums.size(); if (length < 3) return res; sort(nums.begin(), nums.end()); for (int i = 0; i < length; ++i) { if (nums[i] > 0) break; //最小值大于0 if (i > 0 && nums[i] == nums[i - 1]) continue; //处理重复值 int left = i + 1, right = length - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { vector<int> temp = {nums[i], nums[left], nums[right]}; res.push_back(temp); while (left < right && nums[left] == nums[left + 1]) ++left; while (left < right && nums[right] == nums[right - 1]) --right; ++left; --right; } else if (sum > 0) --right; else ++left; } } return res; } };
标签:3sum vector begin style leetcode for while http info
原文地址:https://www.cnblogs.com/ZSY-blog/p/12952461.html