-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_16_3SumClosest.cpp
61 lines (53 loc) · 1.56 KB
/
LC_16_3SumClosest.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
https://leetcode.com/problems/3sum-closest/
16. 3Sum Closest
*/
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(), nums.end());
if(n<3) return 0;
int l, r, ans = 0, sum, diff, min_diff=INT_MAX;
for(int i=0; i<n-2; i++)
{
l = i+1;
r = n-1;
while(l<r)
{
sum = nums[i]+nums[l]+nums[r];
diff = abs(target-sum);
if(diff < min_diff)
{
min_diff = diff;
ans = sum;
}
// if(sum == target)
// return sum;
else if(sum > target)
{
// diff = (sum-target);
// if(diff < min_diff)
// {
// min_diff = diff;
// ans = sum;
// }
r--;
}
else if(sum < target)
{
// diff = (target-sum);
// if(diff < min_diff)
// {
// min_diff = diff;
// ans = sum;
// }
l++;
}
else
return ans;
}
}//for i
return ans;
}//end
};