-
Notifications
You must be signed in to change notification settings - Fork 0
/
p16.cpp
43 lines (41 loc) · 1.04 KB
/
p16.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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int threeSumClosest(vector<int> &nums, int target)
{
int diff = INT_MAX;
int res = 0;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++)
{
int start = i + 1, end = nums.size() - 1;
while (start < end)
{
if (abs(target - (nums[i] + nums[start] + nums[end])) < diff)
{
diff = abs(target - (nums[i] + nums[start] + nums[end]));
res = nums[i] + nums[start] + nums[end];
}
if (diff == 0)
return res;
if (nums[i] + nums[start] + nums[end] < target)
{
start++;
}
else
{
end--;
}
}
}
return res;
}
};
int main()
{
vector<int> v = {0, 0, 0};
cout << Solution().threeSumClosest(v, 1);
return 0;
}