-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
3sum.cpp
34 lines (33 loc) · 1.08 KB
/
3sum.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
// Time: O(n^2)
// Space: O(1)
class Solution {
public:
vector<vector<int>> threeSum(vector<int> &nums) {
sort(begin(nums), end(nums));
vector<vector<int>> result;
for (int i = size(nums) - 1; i >= 2; --i) {
if (i + 1 < size(nums) && nums[i] == nums[i + 1]) {
continue;
}
const auto& target = -nums[i];
int left = 0, right = i - 1;
while (left < right) {
if (nums[left] + nums[right] < target) {
++left;
} else if (nums[left] + nums[right] > target) {
--right;
} else {
result.push_back({nums[left], nums[right], nums[i]});
++left; --right;
while (left < right && nums[left] == nums[left - 1]) {
++left;
}
while (left < right && nums[right] == nums[right + 1]) {
--right;
}
}
}
}
return result;
}
};