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
29 lines (25 loc) · 786 Bytes
/
ThreeSumClosest.java
File metadata and controls
29 lines (25 loc) · 786 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
import java.util.Arrays;
public class ThreeSumClosest {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int min = Integer.MAX_VALUE, res = 0;
for (int k = 0; k < nums.length - 2; k++) {
for (int i = k + 1, j = nums.length - 1; i < j; ) {
int sum = nums[k] + nums[i] + nums[j];
if (sum > target) {
j--;
} else if (sum < target) {
i++;
} else {
return sum;
}
int delta = Math.abs(sum - target);
if (delta < min) {
min = delta;
res = sum;
}
}
}
return res;
}
}