-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3SumClosest.cpp
38 lines (37 loc) · 998 Bytes
/
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
class Solution
{
public:
int threeSumClosest(vector<int>& nums, int target)
{
sort(nums.begin(), nums.end());
int dis = INT_MAX, res = 0;
for(int i = 0; i < nums.size() - 2; i++)
{
int start = i+1, end = nums.size()-1;
while(start < end)
{
sum = nums[i] + nums[start] + nums[end];
if(sum == target)
return target;
else if(sum < target)
{
if(dis > target - sum)
{
dis = target - sum;
res = sum;
}
start++;
}
else {
if(dis > sum - target)
{
dis = sum - target;
res = sum;
}
end--;
}
}
}
return res;
}
}