-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy path15. 3sum.cpp
More file actions
55 lines (55 loc) · 1.25 KB
/
15. 3sum.cpp
File metadata and controls
55 lines (55 loc) · 1.25 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
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
sort(nums.begin(), nums.end());
if (nums.size() < 3)
{
return {};
}
if (nums[0] > 0)
{
return {};
}
vector<vector<int>> answer;
for (int i = 0; i < nums.size(); ++i)
{
if (nums[i] > 0)
{
break;
}
if (i > 0 && nums[i] == nums[i - 1])
{
continue;
}
int low = i + 1, high = nums.size() - 1;
int sum = 0;
while (low < high)
{
sum = nums[i] + nums[low] + nums[high];
if (sum > 0)
{
high--;
}
else if (sum < 0)
{
low++;
}
else
{
answer.push_back({nums[i], nums[low], nums[high]});
int last_low_occurence = nums[low], last_high_occurence = nums[high];
while (low < high && nums[low] == last_low_occurence)
{
low++;
}
while (low < high && nums[high] == last_high_occurence)
{
high--;
}
}
}
}
return answer;
}
};