forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
3sum-closest.cpp
31 lines (31 loc) · 1.09 KB
/
3sum-closest.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
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
sort(num.begin(), num.end());
int sz = num.size(), res = 0, abso = 0x7fffffff;
for(int i = 0; i < sz - 1; ++i) {
if(i > 0 && num[i] == num[i-1])
continue;
int lp = i + 1, rp = sz - 1;
while(lp < rp) {
int sum = num[i] + num[lp] + num[rp];
if(sum == target)
return target;
if(abs(sum - target) < abso) {
res = sum;
abso = abs(sum - target);
}
if(sum > target) {
int tmp = num[rp];
while(lp < --rp && num[rp] == tmp);
} else {
int tmp = num[lp];
while(++lp < rp && num[lp] == tmp);
}
}
}
return res;
}
};