-
Notifications
You must be signed in to change notification settings - Fork 0
/
3closest.cpp
57 lines (44 loc) · 1.42 KB
/
3closest.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
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(num.begin(), num.end());
int len = num.size();
int closest_diff = 999999;
if (len==2)
return num[0] + num[1];
if (len==3)
return num[0] + num[1] + num[2];
int i = 0;
int j = 1;
int k = 2;
int ret = 99999;
while(i<len-2)
{
j = i+1;
while (j< len-1)
{
k=j+1;
while(k<len)
{
int tmp = num[i] + num[j] + num[k];
int current_number = tmp - target;
if (current_number == 0)
return tmp;
if (current_number < 0 )
current_number = 0 - current_number;
if( current_number < closest_diff)
{
closest_diff = current_number;
ret = tmp;
}
k++;
}
j++;
}
i++;
}
return ret;
}
};