class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
int n = nums.size();
if (n < 3)
{
return ans;
}
sort(nums.begin(), nums.end());
for (int first = 0; first < n - 2; first++)
{
if (nums[first] > 0)
{
return ans;
}
if (first > 0 && nums[first] == nums[first - 1])
{
continue;
}
int second = first + 1, third = n - 1;
while (second < third)
{
if (second > first + 1 && nums[second] == nums[second - 1])
{
second++;
continue;
}
if (nums[first] + nums[second] + nums[third] == 0)
{
ans.push_back({ nums[first], nums[second], nums[third] });
second++;
third--;
}
else if (nums[first] + nums[second] + nums[third] > 0)
{
third--;
}
else if (nums[first] + nums[second] + nums[third] < 0)
{
second++;
}
}
}
return ans;
}
};
LeetCode15. 三数之和
最新推荐文章于 2022-10-08 20:34:08 发布