Skip to content

Commit 94f7e7b

Browse files
authored
Adding Solution to 3 Sum in C++ (#132)
* Added solution in c++ for #973 * Added name and details in Contributors * Update README.md * Update README.md * Update README.md * Update README.md * Added Solution to 3 Sum problem in C++ * Update README.md * Delete 3sum.cpp * Update README.md * Add files via upload * Update README.md
1 parent b21c546 commit 94f7e7b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

C++/3sum.cpp

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> threeSum(vector<int>& nums) {
4+
vector<vector<int> > res;
5+
6+
std::sort(nums.begin(), nums.end());
7+
8+
for (int i = 0; i < nums.size(); i++) {
9+
10+
int target = -nums[i];
11+
int front = i + 1;
12+
int back = nums.size() - 1;
13+
14+
while (front < back) {
15+
16+
int sum = nums[front] + nums[back];
17+
18+
// Finding answer which start from number nums[i]
19+
if (sum < target)
20+
front++;
21+
22+
else if (sum > target)
23+
back--;
24+
25+
else {
26+
vector<int> triplet(3, 0);
27+
triplet[0] = nums[i];
28+
triplet[1] = nums[front];
29+
triplet[2] = nums[back];
30+
res.push_back(triplet);
31+
32+
// Processing duplicates of Number 2
33+
// Rolling the front pointer to the next different number forwards
34+
while (front < back && nums[front] == triplet[1]) front++;
35+
36+
// Processing duplicates of Number 3
37+
// Rolling the back pointer to the next different number backwards
38+
while (front < back && nums[back] == triplet[2]) back--;
39+
}
40+
41+
}
42+
43+
// Processing duplicates of Number i
44+
while (i + 1 < nums.size() && nums[i + 1] == nums[i])
45+
i++;
46+
47+
}
48+
49+
return res;
50+
}
51+
};

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,8 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
267267
| 005 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/5_LongestPalindromicSubstring.py) <br> [JavaScript](./JavaScript/5.Longest-Palindromic-Substring.js) | _O(N^2)_ <br> _O(N^2)_ | _O(N)_ <br> _O(1)_ | Medium | | Expand the Wings |
268268
| 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Java](./Java/median-of-two-sorted-arrays.java) | _O(log(min(m,n)))_ | _O(1)_ | Hard | | |
269269
| 845 | [Longest Mountain in Array](https://leetcode.com/problems/longest-mountain-in-array/) | [C++](./C++/Longest-Mountain-in-Array.cpp) | _O(N)_ | _O(1)_ | Medium | Two Pointer |
270+
| 015 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) | _O(N)_ | _O(1)_ | Medium | Two Pointer | |
271+
270272

271273
<br/>
272274
<div align="right">

0 commit comments

Comments
 (0)