-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy path4sum.cpp
More file actions
80 lines (60 loc) · 1.6 KB
/
4sum.cpp
File metadata and controls
80 lines (60 loc) · 1.6 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > results;
int i = 0;
int size = num.size();
sort(num.begin(), num.end());
while (i < (size - 3)) {
int pre_first = num[i];
int j = i + 1;
int tmp;
while (j < (size - 2)) {
int pre_second = num[j];
int two_sum = pre_first + pre_second;
int start = j + 1;
int end = size - 1;
while (start < end) {
int left_val = num[start];
int right_val = num[end];
int four_sum = two_sum + left_val + right_val;
if (four_sum < target) {
++start;
}
else if (four_sum > target) {
--end;
}
else {
vector<int> result;
result.push_back(pre_first);
result.push_back(pre_second);
result.push_back(left_val);
result.push_back(right_val);
results.push_back(result);
tmp = start + 1;
while ((tmp < end) && (num[tmp] == num[start])) {
++tmp;
}
start = tmp;
tmp = end - 1;
while ((tmp > start) && (num[tmp] == num[end])) {
--tmp;
}
end = tmp;
}
}
tmp = j + 1;
while ((tmp < (size - 2)) && (num[tmp] == num[j])) {
++tmp;
}
j = tmp;
}
tmp = i + 1;
while ((tmp < (size - 3)) && (num[tmp] == num[i])) {
++tmp;
}
i = tmp;
}
return results;
}
};