Skip to content

Commit af9e328

Browse files
authored
Create _15.cpp
1 parent 763fd34 commit af9e328

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

cpp/_15.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> threeSum(vector<int>& nums) {
4+
sort(nums.begin(),nums.end());
5+
6+
vector<vector<int>> v;
7+
8+
if(nums.size()<3){
9+
//if vector nums has less than 3 elements, impossible to distribute into 3 element set -> return 0.
10+
return v;
11+
}
12+
13+
for(int i=0;i<nums.size();i++){
14+
15+
if(i>0 and nums[i]==nums[i-1]){
16+
//same elements dont have to be taken.
17+
continue;
18+
}
19+
20+
int l = i+1, r = nums.size()-1;
21+
//Using 2-pointer concept
22+
while(l<r){
23+
int sum = nums[i] + nums[l] + nums[r];
24+
if(sum>0){
25+
r--;
26+
}else if(sum<0){
27+
l++;
28+
}else{
29+
v.push_back(vector<int> {nums[i],nums[l],nums[r]});
30+
while(l<r and nums[l]==nums[l+1]) l++;
31+
while(l<r and nums[r]==nums[r-1]) r--;
32+
l++; r--;
33+
}
34+
}
35+
36+
}
37+
38+
return v;
39+
}
40+
};

0 commit comments

Comments
 (0)