-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path16.cpp
More file actions
25 lines (24 loc) · 764 Bytes
/
16.cpp
File metadata and controls
25 lines (24 loc) · 764 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
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
int difference = INT_MAX;
int res = -1;
for (int i = 0; i < n - 2; ++i) {
int left = i + 1;
int right = n - 1;
while (left < right) {
int currentSum = nums[i] + nums[left] + nums[right];
int currentDiff = abs(target - currentSum);
if (currentDiff < difference) {
difference = currentDiff;
res = currentSum;
}
if (currentSum > target) right--;
else left++;
}
}
return res;
}
};