-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0015-3sum.cpp
More file actions
29 lines (28 loc) · 953 Bytes
/
0015-3sum.cpp
File metadata and controls
29 lines (28 loc) · 953 Bytes
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
#include <algorithm>
#include <vector>
class Solution {
public:
std::vector<std::vector<int>> threeSum(std::vector<int>& nums) {
std::vector<std::vector<int>> result{};
std::sort(nums.begin(), nums.end());
int length = nums.size();
for (int i = 0; i <= length - 3; i++) {
if (nums[i] > 0) break;
if (i >= 1 and nums[i] == nums[i-1]) continue;
int k = length - 1;
for (int j = i + 1; j <= length - 2; j++) {
if (j > i + 1 and nums[j] == nums[j - 1]) continue;
while (j < k and nums[j] + nums[k] > -nums[i]) {
k--;
}
if (j == k) {
break;
}
if (nums[j] + nums[k] == -nums[i]) {
result.push_back(std::vector<int>({nums[i], nums[j],nums[k]}));
}
}
}
return result;
}
};