-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path3_Sum_Closest.cpp
42 lines (36 loc) · 1.24 KB
/
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
class Solution {
public:
// http://en.wikipedia.org/wiki/3SUM
int threeSumClosest(vector<int> &num, int target) {
if(num.empty()) return 0;
sort(num.begin(), num.end());
int min= INT_MAX; // int min = numeric_limit<int>::max();
int record;
for(int i = 0, n = num.size(); i < n - 2; i++) {
int start = i + 1, end = n - 1;
while(start < end) {
int sum = num[start] + num[end] + num[i];
if(sum == target) {
min = 0;
record = sum;
break;
} else if(sum > target) {
if(sum - target < min) {
min = sum - target;
record = sum;
}
end--;
} else if(sum < target) {
if(target - sum < min) {
min = target - sum;
record = sum;
}
start++;
}
while(i < num.size() - 1 and num[i] == num[i + 1])
i++;
}
}
return record;
}
};