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.給定一個整數數組,咱們須要找出數組中三個元素的加和,使這個加和最接近於輸入的target數值。返回這個最接近的加和。題目假設一道題只有一個答案。算法
For example,輸入數組S = {-1 2 1 -4},目標和target = 1.
最接近target的加和是 2. (-1 + 2 + 1 = 2).數組
public int threeSumClosest(int[] nums, int target) { int min = Integer.MAX_VALUE; Arrays.sort(nums); for(int i=0;i<nums.length-2;i++){ int temp = target - nums[i]; int low = i+1; int high = nums.length-1; while(low < high){ int diff = nums[low]+nums[high]-temp; if(diff == 0) return target; if(Math.abs(min) > Math.abs(diff)){ min = diff; } if(diff > 0)high--; else low++; } } return target+min; }