forked from NiharRanjan53/HacktoberFest_2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3Sum
37 lines (35 loc) · 945 Bytes
/
3Sum
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
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
sort(nums.begin(),nums.end());
int n =nums.size();
for(int i=0;i<n;i++)
{
int a = nums[i];
int t=-a;
int s=i+1,e=n-1;
while(s<e)
{
if(nums[s]+nums[e]==t)
{
ans.push_back({nums[i],nums[s],nums[e]});
while(s<e && nums[s]==nums[s+1]) s++;
while(s<e && nums[e]==nums[e-1]) e--;
s++;
e--;
}
else if(nums[s]+nums[e]>t)
{
e--;
}
else
{
s++;
}
}
while(i+1<n && nums[i+1]==nums[i]) i++;
}
return ans;
}
};