-
Notifications
You must be signed in to change notification settings - Fork 8
/
solution.cpp
33 lines (31 loc) · 961 Bytes
/
solution.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
/**
* 318 / 318 test cases passed.
* Runtime: 56 ms
* Memory Usage: 19.5 MB
*/
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
int n = nums.size();
if (n < 3) return ans;
sort(nums.begin(), nums.end());
for (int i = 0; i < n; ++ i) {
if (nums[i] > 0) return ans;
if (i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1, r = n - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
ans.push_back({nums[i], nums[l], nums[r]});
while (l < r && nums[l] == nums[l + 1]) ++ l;
while (l < r && nums[r] == nums[r - 1]) -- r;
++ l;
-- r;
} else if (sum > 0) -- r;
else ++ l;
}
}
return ans;
}
};