-
Notifications
You must be signed in to change notification settings - Fork 0
/
3sum-closest.cpp
45 lines (40 loc) · 1.28 KB
/
3sum-closest.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
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int distToTarget = numeric_limits<int>::max();
int result = -10;
if (num.size() < 3){
return result;
}
map<int, int> hist;
for (int k : num)
hist[k]++;
int n = (int) hist.size();
vector<int> v;
v.reserve(n);
for(auto &p : hist){
v.push_back(p.first);
}
for (int i = 0; i < n; i++){
int fi = hist[v[i]];
int j = (fi >= 2) ? i : i+1;
int k = n - 1;
while (j < k ||
(j == k && j != i && hist[v[j]] >= 2) ||
(i == j && i == k && hist[v[j]] >= 3)
) {
int triSum = v[i] + v[j] + v[k];
int triDiff = triSum - target;
if (triDiff == 0)
return target;
if (abs(triDiff) < distToTarget){
distToTarget = abs(triDiff);
result = triSum;
}
if (triDiff <= 0) j++;
if (triDiff >= 0) k--;
}
}
return result;
}
};