-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum.cpp
More file actions
39 lines (35 loc) · 970 Bytes
/
3sum.cpp
File metadata and controls
39 lines (35 loc) · 970 Bytes
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
/*
https://leetcode.com/problems/3sum/
*/
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
int n=nums.size();
vector<vector<int> > vec;
int a,b,c;
for(int i=0;i<n-2;i++)
{
if(i==0 || nums[i-1]!=nums[i])
{
int j=i+1;
int k=n-1;
while(j<k)
{
int sum=nums[i]+nums[j]+nums[k];
if(sum==0)
{
vec.push_back({nums[i],nums[j],nums[k]});
while(j<k && nums[j]==nums[j+1])j++;
while(j<k && nums[k]==nums[k-1])k--;
j++;
k--;
}
else if(sum>0)k--;
else j++;
}
}
}
return vec;
}
};