Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
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).
思路:同上篇博客,稍加变化而已。
import java.util.Arrays; public class Solution { public int threeSumClosest(int[] nums, int target) { if (nums.length < 3) { return 0; } Arrays.sort(nums); int value = nums[0] + nums[1] + nums[2]; for (int i = 0; i < nums.length; i++) { if (i >= 1 && nums[i] == nums[i - 1]) { continue; } int j = i + 1; int k = nums.length - 1; while (j < k) { int nowValue = nums[i] + nums[j] + nums[k]; if (Math.abs(nowValue - target) < Math.abs(value - target)) { value = nowValue; } if (nowValue > target) { while (k > j && k <= nums.length - 2 && nums[k] == nums[k - 1]) { k--; } k--; } else if (nowValue < target) { while (j < k && j >= 1 && nums[j] == nums[j + 1]) { j++; } j++; } else { return target; } } } return value; } }