16,最接近的三数之和

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        rlt_min = 9999999
        rlt = 0
        for i in range(len(nums)):
            l = i + 1
            r = len(nums) - 1
            while l < r:
                test_min = (nums[i] + nums[l] + nums[r]) - target
                tmp_rlt = nums[i] + nums[l] + nums[r]
                if test_min == 0:
                    return tmp_rlt
                elif test_min < 0:
                    l += 1
                else:
                    r -= 1
                if abs(test_min) < rlt_min:
                    rlt_min = abs(test_min)
                    rlt = tmp_rlt
        return rlt

猜你喜欢

转载自blog.csdn.net/weixin_42758299/article/details/88564861
今日推荐