Skip to content

Commit 7e74ece

Browse files
authored
Create 3-Sum.cpp
1 parent 7b10217 commit 7e74ece

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

cpp/3-Sum.cpp

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> threeSum(vector<int>& nums) {
4+
5+
//
6+
vector<vector<int>> res;
7+
//sort
8+
sort(nums.begin(),nums.end());
9+
10+
for(unsigned int i = 0; i < nums.size();i++){
11+
// initialize left and right
12+
//to handle duplicates
13+
if(i > 0 && nums[i]==nums[i-1])
14+
continue;
15+
int l = i + 1;
16+
int r = nums.size() - 1;
17+
int x = nums[i];
18+
19+
while (l < r)
20+
{
21+
if (x + nums[l] + nums[r] == 0) {
22+
res.push_back(vector<int>{x,nums[l],nums[r]});
23+
//to handle duplicates
24+
while (l<r && nums[l] == nums[l+1])
25+
l++;
26+
// to handle duplicates
27+
while (l<r && nums[r] == nums[r-1])
28+
r--;
29+
l++;
30+
r--;
31+
//break;
32+
}
33+
// If sum of three elements is less
34+
// than zero then increment in left
35+
else if (x + nums[l] + nums[r] < 0)
36+
l++;
37+
38+
// if sum is greater than zero than
39+
// decrement in right side
40+
else
41+
r--;
42+
}
43+
44+
}
45+
return res;
46+
}
47+
};

0 commit comments

Comments
 (0)