-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path16.cpp
More file actions
25 lines (24 loc) · 651 Bytes
/
16.cpp
File metadata and controls
25 lines (24 loc) · 651 Bytes
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
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(),nums.end());
int ans=0;
int d=INT_MAX;
for(int i=0;i<n-2;i++){
int l = i+1;
int r = n-1;
while(l<r){
int sum = nums[i]+nums[l]+nums[r];
if(abs(sum-target)<d){
d = abs(sum-target);
ans = sum;
}
if(sum==target) return sum;
else if(sum>target) r--;
else l++;
}
}
return ans;
}
};