forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeSumCloset.java
72 lines (57 loc) · 2.1 KB
/
TreeSumCloset.java
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
67
68
69
70
71
72
package Algorithms;
import java.util.Arrays;
public class TreeSumCloset {
public static void main(String[] args) {
int[] n = {-10,0,-2,3,-8,1,-10,8,-8,6,-7,0,-7,2,2,-5,-8,1,-4,6};
//int[] n = {0,0,0};
int r = threeSumClosest(n, 18);
System.out.printf("RETUREN: %d\n", r);
}
public static int threeSumClosest(int[] num, int target) {
// first sort the array.
Arrays.sort(num);
int rst = 0;
boolean first = true;
int sum = 0;
for (int i = 0; i <= num.length-3; i++) {
int n2 = i+1;
int n3 = num.length-1;
ok:while (n2 < n3) {
while (n2 - 1 > i && num[n2] == num[n2 - 1]){
n2++;
if (n2 >= n3) {
break ok;
}
}
while (n3 + 1 <= num.length - 1 && num[n3] == num[n3 + 1]) {
n3--;
if (n2 >= n3) {
break ok;
}
}
if (n2 >= n3) {
//break;
}
sum = num[i]+num[n2]+num[n3];
if (sum > target) { // move left.
n3--;
} else if (sum < target) { // move right
n2++;
} else { // can return because it is equal;
System.out.printf("return: %d 1:%d 2:%d 3:%d \n",rst,num[i],num[n2],num[n3]);
return target;
}
}
if (first == true) {
rst = sum;
first = false;
System.out.printf("first: %d \n", rst);
} else if (Math.abs(sum-target) < Math.abs(rst-target)) {
rst = sum;
System.out.printf("later: %d \n", rst);
}
}
System.out.printf("LAST: %d \n", rst);
return rst;
}
}