forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3sum-closest_1_AC.cpp
37 lines (36 loc) · 898 Bytes
/
3sum-closest_1_AC.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
#include <algorithm>
#include <cmath>
using std::abs;
using std::sort;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
vector<int> &a = nums;
int n = a.size();
if (n < 3) {
return 0;
}
sort(a.begin(), a.end());
int res = a[0] + a[1] + a[2];
int i, j, k;
int val;
for (i = 0; i < n - 2; ++i) {
j = i + 1;
k = n - 1;
while (j < k) {
val = a[i] + a[j] + a[k];
if (abs(val - target) < abs(res - target)) {
res = val;
}
if (val < target) {
++j;
} else if (val > target) {
--k;
} else {
return target;
}
}
}
return res;
}
};