For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
[分析] 基于 3 sum的思路求解,先排序,选定第一个元素,然后夹逼法求出当前第一个元素下最接近target的 sum3。注意到closest初始化不要写成整数的最大最小值,不然比较获取局部最优时(if (Math.abs(sum3 - target) < Math.abs(closest - target)))会溢出导致错误结果。
public int threeSumClosest(int[] nums, int target) { if (nums == null || nums.length < 3) return Integer.MAX_VALUE; int N = nums.length; Arrays.sort(nums); int closest = nums[0] + nums[1] + nums[2]; int sum3; for (int k = 0; k < N - 2; k++) { if (k > 0 && nums[k] == nums[k - 1]) continue; int i = k + 1, j = N - 1; while (i < j) { sum3 = nums[i] + nums[j] + nums[k]; if (sum3 == target) { return target; } else if (sum3 > target) { if (Math.abs(sum3 - target) < Math.abs(closest - target)) closest = sum3; while (i < --j && nums[j] == nums[j + 1]); } else { if (Math.abs(sum3 - target) < Math.abs(closest - target)) closest = sum3; while (++i < j && nums[i] == nums[i - 1]); } } } return closest; }