Topic describes

Given an array of n integers nums and a target value target. Identify the three integers in NUMs so that their sum is closest to target. Returns the sum of these three numbers. Assume that there is only one answer for each set of inputs.

Answer key

The solution is similar to the sum of three numbers, except that we no longer need to look at the condition equal to zero. Instead, we are as close to the target number as possible, and update the closest sum according to the difference between target and target.

class Solution { public int threeSumClosest(int[] nums, int target) { int res = nums[0] + nums[1] + nums[nums.length - 1]; Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { int left = i + 1; int right = nums.length - 1; while (left < right) { if (Math.abs(nums[i] + nums[left] + nums[right] - target) < Math.abs(res - target)) { res = nums[i] + nums[left] + nums[right]; } if (nums[i] + nums[left] + nums[right] < target) { left++; } else if (nums[i] + nums[left] + nums[right] > target) { right--; } else { return target; } } } return res; }}Copy the code