-
Notifications
You must be signed in to change notification settings - Fork 0
/
3Sum Closest.cpp
38 lines (33 loc) · 978 Bytes
/
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
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target)
{
int closest = nums[0] + nums[1] + nums[2];
int diff = abs(closest - target);
sort(nums.begin(), nums.end());
for(int i = 0; i < (int)nums.size() - 2; i++)
{
if(nums[i]*3 > target) return min(closest, nums[i] + nums[i+1] + nums[i+2]);
int left = i + 1;
int right = (int)nums.size() - 1;
while(left < right)
{
int sum = nums[i] + nums[left] + nums[right];
int newDiff = abs(sum - target);
if(diff > newDiff)
{
diff = newDiff;
closest = sum;
}
if(sum < target) ++left;
else{
right--;
}
}
}
return closest;
}
};