Loading

leetcode16 最接近三数之和

思路:

首先排序

依次遍历列表中每一个数

再在以这个数为分界的后半部分列表中找两个数,计算三数之和

这两个数通过双指针来指定,左指针为i+1,右指针为lenth-1

如果target大于三数之和,则右指针左移,反之左指针右移;

并且每次计算三数之和后,要更新最接近target的三数之和。

 

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        lenth = len(nums)
        nums.sort()
        best = 10**4
        def update(sum):
            nonlocal best
            if abs(best- target) > abs(sum - target):
                best = sum

        for i in range(lenth-1):
            num_1 = nums[i]
            # if i > 0 and nums[i+1] == num_1:
            #     continue

            left = i+1
            right = lenth-1
            
            while left < right:
                s = num_1 + nums[left] + nums[right]
                if s == target:
                    return s
                update(s)
                if s < target:
                    left +=  1
                elif s > target:
                    right -= 1
        return best

 

posted @ 2021-08-18 11:01  climber_dzw  阅读(21)  评论(0编辑  收藏  举报