Leetcode-16-3Sum-Closest
題目
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
Example 1
1 | Input: nums = [-1,2,1,-4], target = 1 |
Example 2
1 | Input: nums = [0,0,0], target = 1 |
解釋題目
題目會給一個 integer array nums,和一個 integer targets。
在 nums 中找三個整數,這三個整數的總和,要最接近 target。
回傳三個整數的總和
。
思路
- 先排序 nums,之後做雙指針比較好處理。
- 固定一項元素,再利用雙指針,找剩下的兩個元素,目標是
三個元素的總和最接近 target
。 - 如果 target 和 新計算的 sum
之間的距離有更小
,則更新 result。 - 如果新計算的 sum ,比 target 小,則 left++ =>
讓新計算的 sum 會更大,越接近 target
- 如果新計算的 sum ,比 target 大,則 right– =>
讓新計算的 sum 會更小,越接近 target
這題跟 Leetcode-15 很像。
程式碼
1 | class Solution { |
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 記錄程式的地方!
評論