LeetCode(16)3Sum Closest

题目如下:

Python代码:

def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if len(nums)<3:
            return
        nums = sorted(nums)
        s = nums[0]+nums[1]+nums[2]
        detal = abs(s-target)
        for i in range(len(nums)-2):
            l = i+1
            r = len(nums)-1
            while l<r:
                sums = nums[i]+nums[l]+nums[r]
                temp = abs(sums-target)
                if temp<detal:
                    detal = temp
                    s = sums
                if sums<target:
                    l += 1
                else:
                    r -= 1
        return s
原文地址:https://www.cnblogs.com/CQUTWH/p/7200610.html