-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path15.3Sum.cpp
51 lines (48 loc) · 1.17 KB
/
15.3Sum.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
41
42
43
44
45
46
47
48
49
50
51
/*
written by Pankaj Kumar.
country:-INDIA
*/
typedef long long ll ;
const ll INF=1e18;
const ll mod1=1e9+7;
const ll mod2=998244353;
//Add main code here
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
sort(nums.begin(), nums.end());
vector<vector<int>> res;
int n = nums.size();
for (int i = 0; i < n; i++)
{
if (i > 0 && nums[i] == nums[i - 1])
continue;
int j = i + 1, k = n - 1;
while (j < k)
{
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0)
{
res.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)
{
j++;
}
else
{
k--;
}
}
}
return res;
}
};