动态规划篇

16. 3Sum Closest

给定数组sums和目标数target,寻找sums的三个数,使得它们之和最接近于target。

https://leetcode.com/problems/3sum-closest/description/

class Solution:
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums = sorted(nums)
        sum3 = sum(nums[:3])
        min_dis = sys.maxsize
        ans= sum3
        for i in range(len(nums)-2):
            start,end = i+1,len(nums)-1
            while start                 sum3 = sum([nums[i],nums[start],nums[end]])
                dis=sum3-target
                if abs(dis)                     min_dis=abs(dis)
                    ans=sum3
                if dis<0:
                    start += 1
                elif dis>0:
                    end -= 1
                else:
                    return ans
        return ans

你可能感兴趣的:(leetcode)