-
Notifications
You must be signed in to change notification settings - Fork 0
/
4sum.cpp
85 lines (80 loc) · 1.79 KB
/
4sum.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> fourSum(vector<int> &nums)
{
int n = nums.size();
int target;
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
if (n < 4 || nums[0] > 0)
{
return {};
}
for (int i = 0; i < n; i++)
{
if (i == 0 || nums[i] != nums[i - 1])
{
target = 0 - nums[i];
}
else
{
continue;
}
int l = i + 1;
int m = i + 2;
int r = n - 1;
while (l < m && m < r)
{
if (nums[l] + nums[r] + nums[m] == target)
{
ans.push_back({nums[i], nums[l], nums[r], nums[m]});
while (l < m && m < r && nums[l] == nums[l + 1])
{
l++;
}
while (l < m && m < r && nums[m] == nums[m + 1])
{
m++;
}
while (l < m && m < r && nums[r] == nums[r - 1])
{
r--;
}
l++;
r--;
m++;
}
else if (nums[l] + nums[r] + nums[m] < target)
{
if (m < r)
{
m++;
}
else if(m=r-1 && l<m)
{
l++;
}
else{
l++;
}
}
else
{
r--;
}
}
}
return ans;
}
int main()
{
vector<int> x = {1, 0, -1, 0, -2, 2};
vector<vector<int>> ans = fourSum(x);
for (auto i : ans)
{
for (auto j : i)
{
cout << j << ",";
}
}
}