-
Notifications
You must be signed in to change notification settings - Fork 0
/
3SumClosest.cpp
40 lines (37 loc) · 1.08 KB
/
3SumClosest.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
// Source: https://leetcode-cn.com/problems/3sum-closest/description/
// Author: Lianfeng Shen
// Date: 2018-10-25
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int c = INT_MAX;
int r = 0;
int l = nums.size();
if (l < 3) return 0;
sort(nums.begin(), nums.end());
for(int i=0; i < l -2; i++) {
int left = i + 1;
int right = l - 1;
while(left < right) {
int h = nums[i] + nums[left] + nums[right];
if ( h == target)
return target;
else if (h > target) {
if (h - target < c) {
c = h - target;
r = h;
}
right--;
}
else {
if (target - h < c) {
c = target - h;
r = h;
}
left++;
}
}
}
return r;
}
};