-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16. 3Sum Closest.cpp
39 lines (39 loc) · 996 Bytes
/
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
class Solution
{
public:
int threeSumClosest(vector<int> &nums, int target)
{
sort(nums.begin(), nums.end());
int res = INT_MAX;
int n = nums.size();
int diff = INT_MAX;
int poss_ans = INT_MAX;
for (int i = 0; i < n - 2; i++)
{
int k = target - nums[i];
int lo = i + 1, hi = n - 1;
while (lo < hi)
{
int curr = nums[lo] + nums[hi];
if (curr == k)
{
return target;
}
else if (curr < k)
{
lo++;
}
else
{
hi--;
}
if (abs(curr + nums[i] - target) < abs(diff))
{
diff = curr + nums[i] - target;
poss_ans = curr + nums[i];
}
}
}
return poss_ans;
}
};