-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.3-sum.cpp
More file actions
42 lines (42 loc) · 1.03 KB
/
Copy path15.3-sum.cpp
File metadata and controls
42 lines (42 loc) · 1.03 KB
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
/*
* @lc app=leetcode id=15 lang=cpp
*
* [15] 3Sum
*/
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
sort(begin(nums), end(nums));
vector<vector<int>> ret;
for (int i = 0; i < nums.size(); i++)
{
if (i > 0 && nums[i] == nums[i - 1])
continue;
int j = i + 1, k = nums.size() - 1;
while (j < k)
{
int t = nums[i] + nums[j] + nums[k];
if (t == 0)
{
ret.push_back({nums[i], nums[j], nums[k]});
j++;
k--;
while (j < k && nums[j] == nums[j - 1])
j++;
while (j < k && nums[k] == nums[k + 1])
k--;
}
else if (t < 0)
j++;
else
k--;
}
}
return ret;
}
};