forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-sum-closest(AC).cpp
More file actions
46 lines (44 loc) · 1.18 KB
/
3-sum-closest(AC).cpp
File metadata and controls
46 lines (44 loc) · 1.18 KB
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
#include <algorithm>
using namespace std;
class Solution {
public:
/**
* @param numbers: Give an array numbers of n integer
* @param target: An integer
* @return: return the sum of the three integers, the sum closest target.
*/
int threeSumClosest(vector<int> nums, int target) {
vector<int> &a = nums;
int n = a.size();
int i, j, k;
int ans;
sort(a.begin(), a.end());
ans = a[0] + a[1] + a[2];
int s;
for (i = 0; i < n - 2; ++i) {
j = i + 1;
k = n - 1;
while (j < k) {
s = a[i] + a[j] + a[k];
if (s < target) {
if (abs(s - target) < abs(ans - target)) {
ans = s;
}
++j;
} else if (s > target) {
if (abs(s - target) < abs(ans - target)) {
ans = s;
}
--k;
} else {
return target;
}
}
}
return ans;
}
private:
int abs(int x) {
return x >= 0 ? x : -x;
}
};