-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy paththreeSum.cpp
More file actions
105 lines (103 loc) · 2.76 KB
/
threeSum.cpp
File metadata and controls
105 lines (103 loc) · 2.76 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ret;
vector<int> pp;
int zeroctr = 0;
int a,b,c, target;
map<int,int> p,n;
for(auto i : nums) {
if(i == 0) {
zeroctr++;
}
else if(i > 0) {
p[i]++;
}
else {
n[i]++;
}
}
if(zeroctr >= 3) {
pp.push_back(0);
pp.push_back(0);
pp.push_back(0);
ret.push_back(pp);
pp.clear();
}
if(zeroctr > 0) {
for(auto i : p) {
if(i.first == 0) {
continue;
}
a = 0 - i.first;
if(n.find(a) != n.end()) {
pp.push_back(a);
pp.push_back(0);
pp.push_back(i.first);
ret.push_back(pp);
pp.clear();
}
}
}
for(auto i : p) {
for(auto j : p) {
if(i == j)
continue;
target = 0 - (i.first + j.first);
if(n[target] > 0) {
pp.push_back(target);
pp.push_back(i.first);
pp.push_back(j.first);
ret.push_back(pp);
pp.clear();
}
}
target = 0 - (i.first + i.first);
if(n[target] > 1) {
pp.push_back(target);
pp.push_back(i.first);
pp.push_back(i.first);
ret.push_back(pp);
pp.clear();
}
}
for(auto i : n) {
for(auto j : n) {
if(i == j)
continue;
target = 0 - (i.first + j.first);
if(p[target] > 0) {
pp.push_back(i.first);
pp.push_back(j.first);
pp.push_back(target);
ret.push_back(pp);
pp.clear();
}
}
target = 0 - (i.first + i.first);
if(p[target] > 1) {
pp.push_back(i.first);
pp.push_back(i.first);
pp.push_back(target);
ret.push_back(pp);
pp.clear();
}
}
return ret;
}
};
int main()
{
Solution s;
vector<int> nums = {-1,0,1,2,-1,-4,-2};
vector<vector<int>> ret = s.threeSum(nums);
for(auto i : ret) {
for(auto j : i)
cout << j << " ";
cout << endl;
}
return 0;
}