-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16_threeSumClosest.cpp
More file actions
35 lines (35 loc) · 1.05 KB
/
16_threeSumClosest.cpp
File metadata and controls
35 lines (35 loc) · 1.05 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
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int mind = INT_MAX,res,tmps,tmpd,ind = 0;
int begin,end;
while(ind<nums.size()-2&&nums[ind]-target<mind){
tmps = nums[ind];
begin = ind+1;
end = nums.size()-1;
while(begin<end){
tmps+=nums[begin]+nums[end];
tmpd = abs(target-tmps);
if(tmpd<mind){
if(tmpd == 0)
return tmps;
mind = tmpd;
res = tmps;
}
if(tmps<target){
begin++;
while(nums[begin] == nums[begin-1]&&begin<end)
begin++;
}else{
end--;
while(nums[end] == nums[end+1]&&begin<end)
end--;
}
tmps = nums[ind];
}
ind++;
}
return res;
}
};