Skip to content

Commit 94b0266

Browse files
authored
Create 15-3Sum.cpp
C++ solution for 15. 3Sum
1 parent 933ca4a commit 94b0266

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

cpp/15-3Sum.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> threeSum(vector<int>& nums) {
4+
sort(nums.begin(), nums.end());
5+
vector<vector<int>> res;
6+
for (int i = 0; i < nums.size(); ++i) {
7+
int a = nums[i];
8+
// triplet should not contain duplicate elements
9+
if (i > 0 && a == nums[i - 1])
10+
continue;
11+
// 2 ptr approach
12+
int l = i + 1, r = nums.size() - 1;
13+
while (l < r) {
14+
int threeSum = a + nums[l] + nums[r];
15+
if (threeSum > 0)
16+
r -= 1;
17+
else if (threeSum < 0)
18+
l += 1;
19+
else {
20+
// found triplet
21+
res.push_back({ a, nums[l], nums[r] });
22+
l += 1;
23+
// skip duplicates
24+
while (nums[l] == nums[l - 1] && l < r)
25+
l += 1;
26+
}
27+
}
28+
}
29+
return res;
30+
}
31+
};

0 commit comments

Comments
 (0)