-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16. 3Sum Closest.cpp
More file actions
36 lines (26 loc) · 949 Bytes
/
16. 3Sum Closest.cpp
File metadata and controls
36 lines (26 loc) · 949 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
29
30
31
32
33
34
35
36
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(), nums.end());
int resultSum = nums[0] + nums[1] + nums[2];
int minDiff = INT_MAX;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int j = i + 1;
int k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) return target;
else if (sum < target) j++;
else k--;
int diffToTarget = abs(sum - target);
if (diffToTarget < minDiff) {
resultSum = sum;
minDiff = diffToTarget;
}
}
}
return resultSum;
}
};