LeetCode 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).

 


題目標簽: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,不會有差值再小的了。

 

Java Solution:

Runtime beats 86.06% 

完成日期:07/12/2017

關鍵詞:Array

關鍵點:利用twoSum的方法,two pointers 來輔助,每次確定第一個數字,剩下的就是找兩個數字之和的問題了

 

 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 List

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM