-
Notifications
You must be signed in to change notification settings - Fork 0
/
0015.3sum.cpp
71 lines (63 loc) · 1.68 KB
/
0015.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <vector>
using std::vector;
// 找nums[0] + nums[1] + nums[2] == 0 的所有三元组
vector<vector<int>> tree_sum(vector<int>& nums)
{
int n = nums.size();
std::sort(nums.begin(), nums.end(), std::less<int>());
auto bs = [&nums](int v) -> int {
int l = 0, r = nums.size() - 1;
while (l < r) {
int m = (l + r + 1) >> 1;
if (nums[m] <= v) l = m;
else r = m - 1;
}
if (nums[l] != v) return -1;
return l;
};
vector<vector<int>> res;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int m = bs(0 - nums[i] - nums[j]);
if (m != -1 && m > j) {
res.push_back(vector<int>{nums[i], nums[j], nums[m]});
}
while (j + 1 < n && nums[j+1] == nums[j]) {
++j;
}
}
while (i + 1 < n && nums[i+1] == nums[i]) {
++i;
}
}
return res;
}
int main () {
#ifdef LOCAL
freopen("0015.in", "r", stdin);
#endif
int n = 0;
while (std::cin >> n) {
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
std::cin >> nums[i];
}
vector<vector<int>> res = tree_sum(nums);
if (res.size() != 0) {
for (const auto& es : res) {
std::cout << "[";
for (int i = 0; i < 3; ++i) {
printf(",%d" + !i, es[i]);
}
std::cout << "]" << std::endl;
}
} else {
std::cout << "[]" << std::endl;
}
}
return 0;
}