-
Notifications
You must be signed in to change notification settings - Fork 0
/
016three_sum_closest.cpp
46 lines (46 loc) · 1.3 KB
/
016three_sum_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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result;
int closest = INT_MAX;
//handle corner case;
if(nums.size() < 3){
return 0;
}
//sort the numbers;
sort(nums.begin(), nums.end());
//find the closest;
for(auto i = nums.begin(); i<nums.end()-2; ++i){
auto j = i+1;
if((i > nums.begin()) && (*i == *(i-1))){
continue;
}
auto k = nums.end()-1;
while(j < k){
auto sum = *i + *j + *k;
auto distance = abs(sum - target);
if(distance < closest){
closest = distance;
result = sum;
}
//decide j or k who should move next;
if(sum < target){
++j;
while((*j == *(j-1)) && (j < k)){
++j;
}
}
else if(sum > target){
--k;
while((*k == *(k+1)) && (j < k)){
--k;
}
}
else{
return result;
}
}
}
return result;
}
};