16. 3Sum Closest
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).
https://leetcode.com/problems/3sum-closest/#/solutions
http://www.cnblogs.com/EdwardLiu/p/4012459.html
先将数组排个序,然后开始遍历数组,思路跟那道三数之和很相似,都是先确定一个数,然后用两个指针left和right来滑动寻找另外两个数,每确定两个数,我们求出此三数之和,然后算和给定值的差的绝对值存在newDiff中,然后和diff比较并更新diff和结果closest即可:
这道题跟3Sum很像,区别就是要维护一个最小的diff,求出和目标最近的三个和。brute force时间复杂度为O(n^3),优化的解法是使用排序之后2 pointers的方法:
通过排序后的和与零比较, 两头的指针移动少计算不符合的项.
总的时间复杂度为O(n^2+nlogn)=(n^2),空间复杂度是O(n)
public class Solution { public int threeSumClosest(int[] num, int target) { if (num == null || num.length < 3) return 0; Arrays.sort(num); int minDiff = num[0] + num[1] + num[2] - target; int diff = 0; for (int i=num.length-1; i>=2; i--) { if (i<num.length-1 && num[i]==num[i+1]) continue; diff = twoSumClosest(num, 0, i-1, target-num[i]); if (Math.abs(diff) < Math.abs(minDiff)) { minDiff = diff; } } return minDiff + target; } public int twoSumClosest(int[] num, int l, int r, int tar) { int minDif = num[l] + num[r] - tar; int dif = 0; while (l < r) { dif = num[l] + num[r] - tar; if (dif == 0) return dif; if (Math.abs(dif) < Math.abs(minDif)) { minDif = dif; } if (dif < 0) { l++; } else { r--; } } return minDif; } }
for (int i = 0; i < nums.length - 2; i++) {
l++;
r--;
l < r