跳至主要内容

15. 3Sum

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
sort(nums.begin(), nums.end());
vector<vector<int>> res;
for (int i = 0; i < nums.size(); i++)
{
if (i > 0 && nums[i - 1] == nums[i]) continue;
int left = i + 1, right = nums.size() - 1;
while (left < right)
{
int threeSum = nums[i] + nums[left] + nums[right];
if (threeSum < 0) left++;
else if (threeSum > 0) right--;
else
{
res.push_back({nums[i], nums[left], nums[right]});
left++; right--;
while (left < right && nums[left - 1] == nums[left]) left++;
while (left < right && nums[right + 1] == nums[right]) right--;
}
}
}
return res;
}
};
  • T: O(N2)O(N^2)
  • S: O(logN)O(\log N)