-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16.3-sum-closest.cpp
50 lines (38 loc) · 1.07 KB
/
16.3-sum-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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @lc app=leetcode id=16 lang=cpp
*
* [16] 3Sum Closest
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <vector>
#include <utility>
#include <limits.h>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end(), [](int x1, int x2) -> bool { return x1 < x2; });
pair<int, int> minPair = { INT_MAX, INT_MIN };
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1, k = nums.size() - 1; j < k; /* none */) {
int threeSum = nums[i] + nums[j] + nums[k];
if(threeSum == target) {
return target;
}
else if(threeSum > target) {
k--;
}
else {
j++;
}
if(minPair.first > abs(threeSum - target)) {
minPair = { abs(threeSum - target), threeSum };
}
}
}
return minPair.second;
}
};
// @lc code=end