Skip to content

Commit c0a5aad

Browse files
committed
Added 3Sum.cpp in Leetcode
1 parent d18e6e6 commit c0a5aad

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Leetcode/ARRAY/3Sum.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
/*
3+
15. 3Sum
4+
solution C++
5+
O(N-square)
6+
*/
7+
8+
9+
class Solution {
10+
public:
11+
vector<vector<int>> threeSum(vector<int>& nums) {
12+
set<vector<int>> ans;
13+
int n= nums.size();
14+
if(n <3)
15+
return {};
16+
17+
sort(nums.begin(), nums.end()); //for using two pointers technique
18+
19+
for(int i=0; i<n-2; i++){
20+
//now using two pointers to find the second and third
21+
22+
if(i >0 && nums[i] == nums[i-1])
23+
continue;
24+
int start = i+1, end= n-1;
25+
while(start < end){
26+
int sum = nums[i] + nums[start]+ nums[end];
27+
if(sum == 0)
28+
{ ans.insert({nums[i],nums[start], nums[end]}); start +=1;}
29+
30+
else if(sum > 0)
31+
end -=1;
32+
else
33+
start +=1;
34+
35+
}
36+
}
37+
38+
vector<vector<int>> yo;
39+
for(auto i= ans.begin(); i != ans.end(); i++)
40+
yo.push_back(*i);
41+
return yo;
42+
}
43+
};

0 commit comments

Comments
 (0)