1 Star 1 Fork 0

钦某/Code

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
15.三数之和.cpp 1.13 KB
Copy Edit Raw Blame History
钦某 authored 2025-02-25 17:17 +08:00 . 三数之和
/*
* @lc app=leetcode.cn id=15 lang=cpp
*
* [15] 三数之和
*/
// @lc code=start
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n;)
{
int left = i + 1, right = n - 1;
while (left < right)
{
int sum = nums[left] + nums[right];
if (sum == -nums[i])
{
ans.push_back({nums[left], nums[right], nums[i]});
right--,
left++;
while (left < right && nums[right + 1] == nums[right])
right--;
while (left < right && nums[left - 1] == nums[left])
left++;
}
else if (sum > -nums[i])
right--;
else
left++;
}
i++;
while (i < n && nums[i - 1] == nums[i])
i++;
}
return ans;
}
};
// @lc code=end
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/wang-qin928/cpp.git
git@gitee.com:wang-qin928/cpp.git
wang-qin928
cpp
Code
master

Search