-
Notifications
You must be signed in to change notification settings - Fork 0
/
0016_3Sum_Closest.java
31 lines (26 loc) · 1.13 KB
/
0016_3Sum_Closest.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
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums, 0, nums.length);
int closest = nums[0] + nums[1] + nums[2];
for(int i = 0; i < nums.length; i++) {
if(i != 0 && nums[i] == nums[i-1]) continue; // skip duplicates
int left = i + 1;
int right = nums.length - 1;
while(left < right) {
int sum = nums[i] + nums[left] + nums[right];
// update closest
closest = (Math.abs(target - closest) < Math.abs(target - sum)) ? closest : sum;
if(sum == target) {
return target;
} else if(sum > target) {
// advance right, skipping repeated elements
while(--right >= 0 && nums[right] == nums[right + 1]);
} else {
// advance left, skipping repeated elements
while(++left < nums.length && nums[left] == nums[left - 1]);
}
}
}
return closest;
}
}