【Leetcode】3Sum Closest (Sum)

来源:互联网 发布:图像融合的算法 编辑:程序博客网 时间:2024/04/28 04:18

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).
这道题不同之处就在于,如果找不到满足的target,就去找最小差异的结果

所以需要维护一个最小diff 不断更新这个最小的diff,最后返回结果即可

代码来自Code_Ganker

public int threeSumClosest(int[] num, int target) {if (num == null || num.length == 0)return Integer.MIN_VALUE;Arrays.sort(num);int minDiff = num[0] + num[1] + num[2] - target;for (int i = 0; i < num.length - 2; i++) {int curDiff = twoSum(num, i + 1, target - num[i]);if (Math.abs(curDiff) < Math.abs(minDiff))minDiff = curDiff;}return target + minDiff;}public int twoSum(int[] num, int start, int target) {int left = start;int right = num.length - 1;int minDiff = num[start] + num[start + 1] - target;while (left < right) {if (num[left] + num[right] == target)return 0;int curDiff = num[left] + num[right] - target;if (Math.abs(curDiff) < Math.abs(minDiff))minDiff = curDiff;else if (num[left] + num[right] < target)left++;elseright--;}return minDiff;}



0 0