forked from yuzhangcmu/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSumClosest.java
More file actions
executable file
·42 lines (33 loc) · 1.09 KB
/
Copy pathThreeSumClosest.java
File metadata and controls
executable file
·42 lines (33 loc) · 1.09 KB
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
package Algorithms.sequence;
public class ThreeSumClosest {
public int threeSumClosest(int[] num, int target) {
if (num == null) {
return 0;
}
int len = num.length;
int diffMin = Integer.MAX_VALUE;
int ret = 0;
for (int i = 0; i < len; i++) {
int l = i + 1;
int r = len - 1;
while (l < r) {
int diff = target - (num[i] + num[l] + num[r]);
if (Math.abs(diff) < diffMin) {
diffMin = Math.abs(diff);
ret = num[i] + num[l] + num[r];
}
if (diff > 0) {
// move right;
l++;
} else if (diff < 0) {
// move left;
r--;
} else {
// We get the 0 now. There is no way that it would be less than 0.
return ret;
}
}
}
return ret;
}
}