-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.3sum.cpp
More file actions
87 lines (75 loc) · 2.71 KB
/
15.3sum.cpp
File metadata and controls
87 lines (75 loc) · 2.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
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
86
87
#include "testharness.h"
#include <map>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
int size = num.size();
vector<vector<int>> result;
if (size <= 2) return result;
std::map<int, int> nmap;
for (auto iter = num.begin(); iter != num.end(); ++iter)
nmap[*iter]++;
for (auto iter = nmap.begin(); iter != nmap.end(); ++iter) {
if (iter->first == 0) {
if (iter->second > 2) result.push_back({0, 0, 0});
continue;
}
if (iter->second > 1) {
int t = - iter->first - iter->first;
if (nmap.find(t) != nmap.end()) {
if (t > iter->first)
result.push_back({iter->first, iter->first, t});
else
result.push_back({t, iter->first, iter->first});
}
}
auto iter2 = iter;
for (++iter2; iter2 != nmap.end(); ++iter2) {
int t = iter->first + iter2->first;
if (t > 0) break;
if (iter2->first + t >= 0) continue;
if (nmap.find(-t) != nmap.end())
result.push_back({iter->first, iter2->first, -t});
}
}
return result;
}
};
TEST(Solution, test) {
{
vector<int> num({-1, 0, 1, 2, -1, -4});
auto result = threeSum(num);
for (auto iter = result.begin(); iter != result.end(); ++iter) {
std::cout << (*iter)[0] << " " << (*iter)[1] << " " << (*iter)[2] << std::endl;
ASSERT_EQ(0, (*iter)[0] + (*iter)[1]+ (*iter)[2]);
ASSERT_LE((*iter)[0], (*iter)[1]);
ASSERT_LE((*iter)[1], (*iter)[2]);
}
}
{
vector<int> num({1, 1, -2});
auto result = threeSum(num);
for (auto iter = result.begin(); iter != result.end(); ++iter) {
std::cout << (*iter)[0] << " " << (*iter)[1] << " " << (*iter)[2] << std::endl;
ASSERT_EQ(0, (*iter)[0] + (*iter)[1]+ (*iter)[2]);
ASSERT_LE((*iter)[0], (*iter)[1]);
ASSERT_LE((*iter)[1], (*iter)[2]);
}
}
{
vector<int> num({1, 0, -1});
auto result = threeSum(num);
for (auto iter = result.begin(); iter != result.end(); ++iter) {
std::cout << (*iter)[0] << " " << (*iter)[1] << " " << (*iter)[2] << std::endl;
ASSERT_EQ(0, (*iter)[0] + (*iter)[1]+ (*iter)[2]);
ASSERT_LE((*iter)[0], (*iter)[1]);
ASSERT_LE((*iter)[1], (*iter)[2]);
}
}
ASSERT_EQ(2, 1+1);
}