1. 程式人生 > >leetcode 16. 最接近的三數之和 (python)

leetcode 16. 最接近的三數之和 (python)

給定一個包括 n 個整數的陣列 nums和 一個目標值 target。找出 nums中的三個整數,使得它們的和與 target 最接近。返回這三個數的和。假定每組輸入只存在唯一答案。

例如,給定陣列 nums = [-1,2,1,-4], 和 target = 1.

與 target 最接近的三個數的和為 2. (-1 + 2 + 1 = 2).
緊接著上一題三數之和,用相同的思路

程式碼如下

class Solution:
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        res = sum(nums[:3])
        m = abs(res - target)
        for i in range(len(nums)):
            l = i+1
            r = len(nums)-1
            while l < r:
                temp = nums[i] + nums[l] +nums[r]
                if abs(res - target) > abs(temp-target):
                    res = temp
                elif target < temp:
                    r -=1
                else :
                    l +=1
        return res