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.html
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).
題目標籤:Array算法
這道題目給了咱們一個nums array 和一個 target, 讓咱們找到一組三數之和,而且是最接近於target的。因爲咱們作過了三數之和,因此差很少是同樣方法來作這道題(這裏充分說明了,要老老實實順着題號作下去,較先的題目均可以被用來輔助以後的題)。方法就是先sort一下array,爲啥要sort呢,由於要用到two pointers 來遍歷找兩數之和,只有在從小到大排序以後的結果上,才能根據狀況移動left 和right。 當肯定好了第一個數字後,就在剩下的array裏找兩數之和,在加上第一個數字,用這個temp_sum減去target 來獲得temp_diff,若是temp_diff比以前的小,那麼更新diff 和 closestSum。 利用two pointers 特性, 若是temp_sum 比target 小的話,說明咱們須要更大的sum,因此要讓left++以便獲得更大的sum。 若是temp_sum 比target 大的話,咱們就須要更小的sum。若是相等的話,直接return 就能夠了。由於都相等了,那麼差值就等於0,不會有差值再小的了。this
Java Solution:spa
Runtime beats 86.06% rest
完成日期:07/12/2017code
關鍵詞:Arrayhtm
關鍵點:利用twoSum的方法,two pointers 來輔助,每次肯定第一個數字,剩下的就是找兩個數字之和的問題了blog
1 public class Solution 2 { 3 public int threeSumClosest(int[] nums, int target) 4 { 5 // sort the nums array 6 Arrays.sort(nums); 7 int closestSum = 0; 8 int diff = Integer.MAX_VALUE; 9 10 11 // iterate nums array, no need for the last two numbers because we need at least three numbers 12 for(int i=0; i<nums.length-2; i++) 13 { 14 int left = i + 1; 15 int right = nums.length - 1; 16 17 // use two pointers to iterate rest array 18 while(left < right) 19 { 20 int temp_sum = nums[i] + nums[left] + nums[right]; 21 int temp_diff = Math.abs(temp_sum - target); 22 // if find a new closer sum, then update sum and diff 23 if(temp_diff < diff) 24 { 25 closestSum = temp_sum; 26 diff = temp_diff; 27 } 28 29 if(temp_sum < target) // meaning need larger sum 30 left++; 31 else if(temp_sum > target) // meaning need smaller sum 32 right--; 33 else // meaning temp_sum == target, this is the closestSum 34 return temp_sum; 35 } 36 } 37 38 return closestSum; 39 } 40 }
參考資料:N/A排序
LeetCode 算法題目列表 - LeetCode Algorithms Questions Listthree