-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3SumClosest.cpp
More file actions
28 lines (28 loc) · 807 Bytes
/
3SumClosest.cpp
File metadata and controls
28 lines (28 loc) · 807 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
26
27
28
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
std::ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
sort(nums.begin(), nums.end());
int res = nums[0] + nums[1] + nums[2];
for(int i= 0; i< nums.size() - 2; i++){
int j = i+1;
int k = nums.size() -1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(abs(sum - target) < abs(res - target)){
res = sum;
}
if(sum < target){
j++;
}else if(sum > target){
k--;
}else{
return target;
}
}
}
return res;
}
};