Skip to content

Commit 234a608

Browse files
author
Danieldu
committed
add 3sum
1 parent 486b122 commit 234a608

File tree

2 files changed

+51
-27
lines changed

2 files changed

+51
-27
lines changed

150/15.3-sum.cpp

Lines changed: 0 additions & 27 deletions
This file was deleted.

TwoPointers/15.3-sum.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
* @lc app=leetcode id=15 lang=cpp
3+
*
4+
* [15] 3Sum
5+
*/
6+
7+
// @lc code=start
8+
#include <bits/stdc++.h>
9+
using namespace std;
10+
11+
class Solution {
12+
public:
13+
vector<vector<int>> threeSum(vector<int>& nums) {
14+
vector<vector<int>> res;
15+
sort(nums.begin(), nums.end());
16+
17+
int n = nums.size();
18+
19+
for (int i = 0; i < n - 2; ++i) {
20+
21+
if (nums[i] > 0) break;
22+
23+
if (i > 0 && nums[i] == nums[i - 1]) continue;
24+
25+
int left = i + 1;
26+
int right = n - 1;
27+
28+
while (left < right) {
29+
long long total = nums[i] + nums[left] + nums[right];
30+
31+
if (total < 0) {
32+
left++;
33+
} else if (total > 0) {
34+
right--;
35+
} else {
36+
res.push_back({nums[i], nums[left], nums[right]});
37+
38+
left++;
39+
while (left < right && nums[left] == nums[left - 1])
40+
left++;
41+
right--;
42+
while (left < right && nums[right] == nums[right + 1])
43+
right--;
44+
}
45+
}
46+
}
47+
return res;
48+
}
49+
};
50+
// @lc code=end
51+

0 commit comments

Comments
 (0)