forked from VivekDubey9/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
3sum.cpp
43 lines (40 loc) · 1.11 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
35
36
37
38
39
40
41
42
43
// 3 SUM Solution
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int N = nums.size();
vector<vector<int>> result;
if (N < 2) {
result;
}
sort(begin(nums), end(nums));
for (int i = 0; i < N - 2 && nums[i] <= 0; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = N - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum < 0) {
j++;
}
else if (sum > 0) {
k--;
}
else {
result.push_back({nums[i], nums[j], nums[k]});
k--;
while (j < k && nums[k] == nums[k + 1]) {
k--;
}
j++;
while (j < k && nums[j] == nums[j - 1]) {
j++;
}
}
}
}
return result;
}
};