Skip to content

Commit 2cd73be

Browse files
committed
add threeSum.cpp
1 parent c67c6de commit 2cd73be

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

C++/threeSum.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Time Complexity: O(n^2)
2+
// Space Complexity: O(1)
3+
4+
class Solution {
5+
public:
6+
vector<vector<int> > threeSum(vector<int> &num) {
7+
vector<vector<int> > ans;
8+
const int target = 0;
9+
10+
if(num.size() < 3)
11+
return ans;
12+
13+
sort(num.begin(), num.end());
14+
auto last = num.end();
15+
for(auto a = num.begin(); a < prev(last, 2); ++a) {
16+
if(a > num.begin() && *a == *(a - 1))
17+
continue;
18+
auto b = next(a);
19+
auto c = prev(last);
20+
21+
while(b < c) {
22+
if(b > next(a) && *b == *(b - 1)) {
23+
++b;
24+
}
25+
else if(c < prev(last) && *c == *(c + 1)) {
26+
--c;
27+
}
28+
else {
29+
const int sum = *a + *b + *c;
30+
31+
if(sum < target)
32+
++b;
33+
else if(sum > target)
34+
--c;
35+
else {
36+
ans.push_back({ *a, *b, *c});
37+
++b;
38+
--c;
39+
}
40+
}
41+
}
42+
}
43+
44+
return ans;
45+
}
46+
};
47+

C++/threeSum2.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Time Complexity: O(n^2)
2+
// Space Complexity: O(1)
3+
4+
class Solution {
5+
public:
6+
vector<vector<int> > threeSum(vector<int> &num) {
7+
vector<vector<int> > ans;
8+
const int target = 0;
9+
10+
sort(num.begin(), num.end());
11+
auto last = num.rend();
12+
for(auto a = num.rbegin(); a < prev(last, 2); ++a) {
13+
if(a > num.rbegin() && *a == *(a - 1))
14+
continue;
15+
auto b = next(a);
16+
auto c = prev(last);
17+
18+
while(b < c) {
19+
if(b > next(a) && *b == *(b - 1)) {
20+
++b;
21+
}
22+
else if(c < prev(last) && *c == *(c + 1)) {
23+
--c;
24+
}
25+
else {
26+
const int sum = *a + *b + *c;
27+
28+
if(sum < target)
29+
--c;
30+
else if(sum > target)
31+
++b;
32+
else {
33+
ans.push_back({ *c, *b, *a});
34+
++b;
35+
--c;
36+
}
37+
}
38+
}
39+
}
40+
41+
return ans;
42+
}
43+
};
44+

0 commit comments

Comments
 (0)