forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_15.cpp
40 lines (33 loc) · 1.13 KB
/
_15.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> v;
if(nums.size()<3){
//if vector nums has less than 3 elements, impossible to distribute into 3 element set -> return 0.
return v;
}
for(int i=0;i<nums.size();i++){
if(i>0 and nums[i]==nums[i-1]){
//same elements dont have to be taken.
continue;
}
int l = i+1, r = nums.size()-1;
//Using 2-pointer concept
while(l<r){
int sum = nums[i] + nums[l] + nums[r];
if(sum>0){
r--;
}else if(sum<0){
l++;
}else{
v.push_back(vector<int> {nums[i],nums[l],nums[r]});
while(l<r and nums[l]==nums[l+1]) l++;
while(l<r and nums[r]==nums[r-1]) r--;
l++; r--;
}
}
}
return v;
}
};