forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0016.cpp
More file actions
27 lines (24 loc) · 734 Bytes
/
0016.cpp
File metadata and controls
27 lines (24 loc) · 734 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
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3) return 0;
int ans = nums[0] + nums[1] + nums[2];
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; i++) {
int l = i + 1;
int r = nums.size() - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum == target)
return sum;
else if (abs(sum - target) < abs(ans - target))
ans = sum;
else if (sum < target)
l++;
else
r--;
}
}
return ans;
}
};