-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path3Sum_Closest.cpp
37 lines (30 loc) · 994 Bytes
/
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
// http://oj.leetcode.com/problems/3sum-closest/
// Time Complexity: O(n^3)
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int result = 0;
int min_gap = INT_MAX;
sort(num.begin(), num.end());
for (auto a = num.begin(); a != prev(num.end(), 2); a = upper_bound(a, prev(num.end(), 2), *a))
{
auto b = next(a);
auto c = prev(num.end());
while (b < c)
{
const int sum = *a + *b + *c;
const int gap = abs(sum - target);
if (gap < min_gap)
{
result = sum;
min_gap = gap;
}
if (sum < target)
b = upper_bound(b, c, *b);
else
c = prev(lower_bound(b, c, *c));
}
}
return result;
}
};