-
Notifications
You must be signed in to change notification settings - Fork 0
/
3Sum Closest.cpp
32 lines (30 loc) · 932 Bytes
/
3Sum Closest.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
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int closest_sum = 0;
int min_d = INT_MAX;
int N = nums.size();
sort(nums.begin(), nums.end());
for(int first = 0; first < N -2; first++){
int second = first + 1;
int third = N -1;
int sum;
while(second < third){
sum = nums[first] + nums[second] + nums[third];
if(sum < target)
second++;
else if(sum > target)
third--;
else if(sum == target){
return target;
}
int d = sum > target? (sum-target):(target-sum);
if( d < min_d){
min_d = d;
closest_sum = sum;
}
}
}
return closest_sum;
}
};