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.
Analysis
思路,类似于 3 Sum 问题,不同之处在于寻找与target的绝对值最小的数;同样可以利用two pointers,对于 a + b + c 中的 b, c 来作为两个指针,a 为 num[i], 那么b初始值则为 num[i + 1], c初始值为num[len - 1]; 通过比较每次 a + b + c 的sum与target的大小,来确定移动b,或者移动c。
Solution
publicclassSolution { /** * @param numbers: Give an array numbers of n integer * @param target : An integer * @return : return the sum of the three integers, the sum closest target. */publicintthreeSumClosest(int[] numbers,int target) {if (numbers ==null||numbers.length<3) {returnInteger.MAX_VALUE; }Arrays.sort(numbers);int diff =Integer.MAX_VALUE/2;int length =numbers.length;int sign =1;for (int i =0; i < length -2; i++) {int pl = i +1;int pr = length -1;while (pl < pr) {int sum = numbers[i] + numbers[pl] + numbers[pr];if (sum == target) {return sum; } elseif (sum < target) {if (target - sum < diff) { diff = target - sum; sign =-1; } pl++; } else {if (sum - target < diff) { diff = sum - target; sign =1; } pr--; } } }return target + sign * diff; }}