-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (27 loc) · 778 Bytes
/
Copy pathSolution.java
File metadata and controls
33 lines (27 loc) · 778 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
import java.util.*;
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closest = Integer.MAX_VALUE;
int n = nums.length;
for (int i = 0; i < n - 2; i++) {
int j = i + 1;
int k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) {
return target;
}
if (Math.abs(sum - target) < Math.abs(closest - target)) {
closest = sum;
}
if (sum > target) {
k--;
} else {
j++;
}
}
}
return closest;
}
}