forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSumClosest.java
More file actions
34 lines (26 loc) · 865 Bytes
/
ThreeSumClosest.java
File metadata and controls
34 lines (26 loc) · 865 Bytes
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
import java.util.Arrays;
public class ThreeSumClosest {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
long dis = Integer.MAX_VALUE, result = 0;
for (int i = 0; i < nums.length - 2; i++) {
int newTarget = target - nums[i];
for (int j = i + 1, k = nums.length - 1; j < k; ) {
int sum = nums[j] + nums[k];
if (sum > newTarget) {
k--;
} else if (sum < newTarget) {
j++;
} else {
return target;
}
long delta = Math.abs(newTarget - sum);
if (delta < dis) {
dis = delta;
result = sum + nums[i];
}
}
}
return (int) result;
}
}