-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOctomber_8.cpp
37 lines (34 loc) · 907 Bytes
/
Octomber_8.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
// https://leetcode.com/problems/3sum-closest/description/
// 16. 3Sum Closest
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
// -4 -1 1 1 2 2
int n = nums.size();
int ans = 1e7;
int sum = 0;
sort(nums.begin(),nums.end());
for(int i=0;i<n;i++){
int k = nums[i];
sum = 0;
int st = i+1;
int en = n-1;
while(st<en){
sum = nums[st] + nums[en] + k;
if(abs(ans-target) > abs(sum-target)){
ans = sum;
}
if(sum == target){
return target;
}
else if(sum<target){
st++;
}
else{
en--;
}
}
}
return ans;
}
};