1. 程式人生 > >Leetcode演算法——16、最接近的三數之和

Leetcode演算法——16、最接近的三數之和

題目

給定一個數組,包含n個整數,以及一個目標整數。要求在陣列中找到三個數,使得這三個數之和最接近目標整數,返回三數之和。

假設每個輸入都只有一個答案。

Given an array nums of n integers 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.

示例:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

思路

參考Leetcode演算法——15、三數求和,也是外層迴圈+首尾指標,只不過本題需要記錄每一次與target的差值,並將最小差值儲存下來。最後通過最小差值和target,便可以反推出三數之和。

python實現

def threeSumClosest(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    與第15題思想類似,也是外層迴圈+首尾指標,只不過本題需要記錄每一次與target的差值,並將最小差值儲存下來。
    
    """
if len(nums) < 3: return [] nums.sort() min_diff = sum(nums[:3]) - target for i in range(len(nums) - 2): if i > 0 and nums[i-1] == nums[i]: # 避免i重複 continue l, r = i + 1, len(nums) - 1 while l < r: diff = nums[
i] + nums[l] + nums[r] - target if diff == 0: # 正好等於target,直接返回,肯定是最小差值 return target else: if abs(diff) < abs(min_diff): # 更新最小差值 min_diff = diff # 根據diff大小判斷哪個指標需要移動 if diff < 0: # 三數之和不夠則往右走 l += 1 else: # 三數之和過大則往左走 r -= 1 return min_diff + target if '__main__' == __name__: nums = [-1, 0, 1, 1, 55] target = 3 print(threeSumClosest(nums, target))