-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum-closest(AC).cpp
More file actions
48 lines (44 loc) · 917 Bytes
/
Copy path3sum-closest(AC).cpp
File metadata and controls
48 lines (44 loc) · 917 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
37
38
39
40
41
42
43
44
45
46
47
48
// 2TLE, 1AC, O(n^2) solution, linear scan is faster than binary search.
#include <algorithm>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int n = (int)num.size();
if (n < 3) {
return 0;
}
int i, j, k;
int res;
int sum;
// sort the array for linear scan
sort(num.begin(), num.end());
// intialize with whatever result here
res = num[0] + num[1] + num[2];
for (i = 0; i < n; ++i) {
j = i + 1;
k = n - 1;
while (j < k) {
sum = num[i] + num[j] + num[k];
if (sum < target) {
++j;
if (myabs(sum - target) < myabs(res - target)) {
res = sum;
}
} else if (sum > target) {
--k;
if (myabs(sum - target) < myabs(res - target)) {
res = sum;
}
} else {
return target;
}
}
}
return res;
}
private:
int myabs(const int n) {
return (n >= 0 ? n : -n);
}
};