forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum-closest.cpp
More file actions
32 lines (26 loc) · 806 Bytes
/
Copy path3sum-closest.cpp
File metadata and controls
32 lines (26 loc) · 806 Bytes
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
// 3Sum Closest
// 先排序,然后左右夹逼//
// Time Complexity: O(n^2), Space Complexity: O(1)
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result = 0;
int min_gap = INT_MAX;
sort(nums.begin(), nums.end());
for (auto a = nums.begin(); a != prev(nums.end(), 2); ++a) {
auto b = next(a);
auto c = prev(nums.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;
else --c;
}
}
return result;
}
};