16. 3Sum Closest(找出和最接近給定值的三個數)
阿新 • • 發佈:2018-12-23
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).
題目大意:給定一個長度為n的整型陣列和一個整數target,在陣列中找出三個數,它們的和最接近target。可以認為對於每個測試用例,解決方案都是唯一的。
解題思路:類似《15. 3Sum(求陣列中和為0的3個數)》,對於要求三個數的和,可以先對陣列從小到大排序,然後鎖定一個數nums[i],根據雙指標的思路從陣列兩端到中間遍歷,找到兩個數nums[left]和nums[right],使得nums[left]+nums[right]+nums[i]的和最接近target。遍歷過程中使用兩個整數diff和res記錄當前獲得的最優解,其中res表示到目前為止找到的最接近target的三個數的和,diff表示target與res的差的絕對值。當遍歷到res==target,已經是最佳方案了,直接返回。
解題程式碼:(22ms,beats 65.39%)
class Solution { public int threeSumClosest(int[] nums, int target) { int diff = Integer.MAX_VALUE; int res = 0; int len = nums.length; Arrays.sort(nums); for (int i = 0; i < len; i++) { int left = i + 1; int right = len - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == target) { return sum; } if (Math.abs(sum - target) < diff) { diff = Math.abs(sum - target); res = sum; } if (sum > target) { right--; } else { left++; } } } return res; } }