-
Notifications
You must be signed in to change notification settings - Fork 0
/
16_3Sum Closest [2].cpp
40 lines (38 loc) · 1.03 KB
/
16_3Sum Closest [2].cpp
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
37
38
39
40
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int ans = 0, closest = INT_MAX;
for (int i = 0; i < nums.size()-2; ++i) {
int second = i+1, third = nums.size()-1;
while (second < third) {
int val = nums[i]+nums[second]+nums[third];
if (abs(val - target) < closest) {
closest = abs(val - target);
ans = val;
}
if (val > target) {
third--;
} else if (val < target) {
second++;
} else {
return target;
}
}
}
return ans;
}
};
int main() {
Solution s;
int n, target;
cin >> n >> target;
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}
cout << s.threeSumClosest(nums, target);
return 0;
}