-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.三数之和.cpp
50 lines (50 loc) · 1.33 KB
/
15.三数之和.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* @lc app=leetcode.cn id=15 lang=cpp
*
* [15] 三数之和
*/
#include "a_header.h"
// @lc code=start
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
vector<vector<int>> ret;
sort(nums.begin(), nums.end());
for (size_t i = 0; i < nums.size() - 2; i++)
{
int target = -nums[i];
int left = i + 1, right = nums.size() - 1;
while (left < right)
{
if (nums[left] + nums[right] == target)
{
ret.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] + nums[right] == target)
{
left++;
}
while (left < right && nums[left] + nums[right] == target)
{
right--;
}
while (i < nums.size() - 2 && -nums[i + 1] == target)
{
i++;
}
}
else if (nums[left] + nums[right] < target)
{
left++;
}
else
{
right--;
}
}
}
return ret;
}
};
// @lc code=end