-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cpp
More file actions
65 lines (55 loc) · 1.5 KB
/
Copy pathSolution.cpp
File metadata and controls
65 lines (55 loc) · 1.5 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
56
57
58
59
60
61
62
63
64
65
#include "Solution.h"
#include <algorithm>
/**
* @brief Complexity
* - Time: O(nlog(n) + n(n-1)) ~ O(n2)
* - Space: O(logn) // sort
*/
std::vector<std::vector<int>> Solution::threeSum(std::vector<int>& nums) {
std::vector<std::vector<int>> trips{};
const size_t size = nums.size();
if (size < 3) {
return trips;
}
std::sort(nums.begin(), nums.end());
// after sorted, if the smallest number is greater than 0,
// no triplet can sum to zero
if (nums[0] > 0) {
return {};
}
for (size_t i = 0; i < size - 2; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) {
// we should not use num[i] == num[i+1] expression because we
// may fall thorough out
continue; // skip duplicates for the 1st
}
int first = nums[i];
// use two pointers to find the 2 remain numbers
size_t j = i + 1;
size_t k = size - 1;
while (j < k) {
int second = nums[j];
int third = nums[k];
int sum = first + second + third;
if (sum == 0) {
trips.push_back({first, second, third});
++j;
--k;
// move next
while (j < k && nums[j] == nums[j - 1]) {
++j; // skip duplicates for the 2nd
}
while (j < k && nums[k] == nums[k + 1]) {
--k; // skip duplicates for the 3rd
}
} else if (sum < 0) {
// require a large sum by increasing the 2nd
++j;
} else {
// require a smaller sum by decreasing the 3rd
--k;
}
}
}
return trips;
}