-
Notifications
You must be signed in to change notification settings - Fork 0
/
16-3SumClosest.cpp
66 lines (61 loc) · 1.75 KB
/
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
62
63
64
65
66
/*=============================================================================
# FileName: 16-3SumClosest.cpp
# Desc:
# Author: qsword
# Email: huangjian1993@gmail.com
# HomePage:
# Created: 2015-04-05 05:18:02
# Version: 0.0.1
# LastChange: 2015-04-06 08:41:06
# History:
# 0.0.1 | qsword | init
=============================================================================*/
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <vector>
using namespace std;
class Solution {
public:
//20ms
int threeSumClosest(vector<int> &num, int target) {
int closet = num[0] + num[1] + num[2];
vector<int> temp(3, 0);
if (num.size() < 3) {
return closet;
}
sort(num.begin(), num.end());
for (int i = 0; i < num.size() - 2; i ++) {
temp[0] = num[i];
int l = i + 1, r = num.size() - 1;
while (l < r) {
int deta = num[i] + num[l] + num[r] - target;
if (deta == 0) {
return target;
} else if (deta > 0) {
if (deta < abs(closet - target)) {
closet = deta + target;
}
r --;
} else {
if (-deta < abs(closet - target)) {
closet = deta + target;
}
l ++;
}
}
}
return closet;
}
};
int main() {
/*int num[] = {0, 0, 0};
vector<int> vec;
for (int i = 0; i < sizeof(num) / sizeof(int); i ++) {
vec.push_back(num[i]);
}
Solution solution;
solution.threeSum(vec);*/
return 0;
}