-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leetcode16.cpp
34 lines (34 loc) · 1.03 KB
/
Leetcode16.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
class Solution {
public:
// use two pointers
// the link of the problem: https://leetcode.cn/problems/3sum-closest/description/
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int ans = nums[0]+nums[1]+nums[2];
int a,b,c;
for(int i = 0; i<nums.size()-2;i++){
a = nums[i];
int left = i+1;
int right = nums.size()-1;
while(left<right){
b = nums[left]; c = nums[right];
if(a+b+c<target){
if(abs(ans-target)>abs(a+b+c-target)){
ans = a+b+c;
}
left++;
continue;
}
if(a+b+c>target){
if(abs(ans-target)>abs(a+b+c-target)){
ans = a+b+c;
}
right--;
continue;
}
return a+b+c;
}
}
return ans;
}
};