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
| class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int n = nums.length, ans = nums[0] + nums[1] + nums[2]; for (int i = 0; i < n - 2; ++i) { if (i > 0 && nums[i] == nums[i - 1]) continue;
int t = nums[i] + nums[i + 1] + nums[i + 2]; if (t > target) { if (t - target < Math.abs(ans - target)) { ans = t; } break; }
t = nums[i] + nums[n - 2] + nums[n - 1]; if (t < target) { if (target - t < Math.abs(ans - target)) { ans = t; } continue; }
int j = i + 1, k = n - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; if (sum == target) return sum; if (Math.abs(sum - target) < Math.abs(ans - target)) ans = sum; if (sum < target) ++j; else --k; } } return ans; } }
|