-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path016_3Sum_Closest.cpp
More file actions
28 lines (26 loc) · 916 Bytes
/
Copy path016_3Sum_Closest.cpp
File metadata and controls
28 lines (26 loc) · 916 Bytes
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
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int ans = (1 << 30);
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++) {
int m = i + 1, r = nums.size() - 1;
while(m < r) {
while(m < r && nums[i] + nums[m] + nums[r] - target < 0) {
ans = getClosest(ans, nums[i] + nums[m] + nums[r], target), m++;
}
while(m < r && nums[i] + nums[m] + nums[r] - target > 0) {
ans = getClosest(ans, nums[i] + nums[m] + nums[r], target), r--;
}
if(m < r && nums[i] + nums[m] + nums[r] - target == 0)
return target;
m++;
}
}
return ans;
}
private:
int getClosest(int a, int b, int t) {
return abs(a - t) < abs(b - t) ? a : b;
}
};