3Sum Closest Medium
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).
public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int closest = Integer.MAX_VALUE; int i = 0; while (i < nums.length - 2) { int j = i + 1; int k = nums.length - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; if (closest == Integer.MAX_VALUE || Math.abs(closest - target) > Math.abs(sum - target)) { closest = sum; } if (sum == target) return sum; if (sum <= target) while (nums[j] == nums[++j] && j < k) ; if (sum >= target) while (nums[k--] == nums[k] && j < k) ; } while (nums[i] == nums[++i] && i < nums.length - 2) ; } return closest; }
思路:与上一题一致,不同处:在判断Sum时不是看是不是=0,而是看是不是更接近target。