-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy path4Sum.cpp
More file actions
58 lines (55 loc) · 1.71 KB
/
4Sum.cpp
File metadata and controls
58 lines (55 loc) · 1.71 KB
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
class Solution
{
public:
vector<vector<int> > fourSum(vector<int> &num, int target)
{
sort(num.begin(), num.end());
if (num.size() >= 4)
{
size_t left = 4;
for (size_t right = 4; right < num.size(); ++right)
{
if (num[right] != num[right - 1] || num[right] != num[right - 2] || num[right] != num[right - 3] || num[right] != num[right - 4])
{
num[left++] = num[right];
}
}
num.erase(num.begin() + left, num.end());
}
vector<vector<int>> result;
vector<int> four(4);
for (size_t c = 2; c < num.size(); ++c)
{
for (size_t d = c + 1; d < num.size(); ++d)
{
int sum2 = num[c] + num[d];
size_t a = 0, b = c - 1;
while (a < b)
{
int sum4 = sum2 + num[a] + num[b];
if (sum4 < target)
{
++a;
}
else if (sum4 > target)
{
--b;
}
else
{
four[0] = num[a];
four[1] = num[b];
four[2] = num[c];
four[3] = num[d];
result.push_back(four);
++a;
--b;
}
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};