forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16.3sum-closest.cpp
44 lines (37 loc) · 1.03 KB
/
16.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
class Solution {
private:
int twoSum(vector<int>& nums, int start, int target, int result){
int left = start + 1;
int right = nums.size() - 1;
while(left < right){
int candidate = nums[start] + nums[left] + nums[right];
if (abs(candidate - target) < abs(result - target))
{
result = candidate;
}
if (candidate > target)
{
right -= 1;
}
else if(candidate < target)
{
left += 1;
}
else
{
break;
}
}
return result;
}
public:
int threeSumClosest(vector<int>& nums, int target) {
int result = nums[0] + nums[1] + nums[3];
sort(nums.begin(), nums.end());
for (auto i = 0; i < nums.size(); ++i)
{
result = twoSum(nums, i, target, result);
}
return result;
}
};