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