题目:
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).
思路:
和3sum一样,排序之后,先确定第一个元素,然后对余下元素进行两边夹。
package sum;import java.util.Arrays;public class ThreeSumClosest {public int threeSumClosest(int[] nums, int target) {int len = nums.length;Arrays.sort(nums);int delta = nums[0] + nums[1] + nums[2] - target;for (int i = 0; i < len - 2;) {int l = i + 1;int r = len - 1;while (l < r) {int tmp = nums[i] + nums[l] + nums[r] - target;if (Math.abs(tmp) < Math.abs(delta))delta = tmp;if (tmp == 0)return target;if (tmp < 0)++l;else--r;}do { ++i; } while (i < len && nums[i] == nums[i - 1]);}return target + delta;}public static void main(String[] args) {// TODO Auto-generated method stubint[] nums = { -1, 2, 1, -4 };int target = 1;ThreeSumClosest t = new ThreeSumClosest();System.out.println(t.threeSumClosest(nums, target));}}