-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path15.三数之和.cpp
58 lines (53 loc) · 994 Bytes
/
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
51
52
53
54
55
56
57
58
/*
* @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>> result;
int len = nums.size();
std::sort(nums.begin(), nums.end());
for (int i = 0; i < len - 2; ++i)
{
if (nums[i] > 0)
{
break;
}
if (i > 0 && nums[i] == nums[i - 1])
{
continue;
}
int j = i + 1;
int k = len - 1;
while (j < k)
{
auto sum = nums[i] + nums[j] + nums[k];
if (sum == 0)
{
result.push_back({nums[i], nums[j], nums[k]});
for (++j; j < k && nums[j] == nums[j - 1]; ++j)
{
}
for (--k; j < k && nums[k] == nums[k + 1]; --k)
{
}
}
else if (sum < 0)
{
++j;
}
else
{
--k;
}
}
}
return result;
}
};
// @lc code=end