-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy path4Sum.cpp
67 lines (50 loc) · 1.64 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
// 4 Sum - Leetcode
// https://leetcode.com/problems/4sum/
class Solution
{
public:
vector<vector<int>> fourSum(vector<int> &num, int target)
{
vector<vector<int>> res;
if (num.empty())
return res;
int n = num.size();
sort(num.begin(), num.end());
for (int i = 0; i < n; i++)
{
int target_3 = target - num[i];
for (int j = i + 1; j < n; j++)
{
int target_2 = target_3 - num[j];
int front = j + 1;
int back = n - 1;
while (front < back)
{
int two_sum = num[front] + num[back];
if (two_sum < target_2)
front++;
else if (two_sum > target_2)
back--;
else
{
vector<int> quadruplet(4, 0);
quadruplet[0] = num[i];
quadruplet[1] = num[j];
quadruplet[2] = num[front];
quadruplet[3] = num[back];
res.push_back(quadruplet);
while (front < back && num[front] == quadruplet[2])
++front;
while (front < back && num[back] == quadruplet[3])
--back;
}
}
while (j + 1 < n && num[j + 1] == num[j])
++j;
}
while (i + 1 < n && num[i + 1] == num[i])
++i;
}
return res;
}
};