Login light

思路跟15题是一样的

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        # print(nums)
        lenNums = len(nums)
        #返回值
        retNum = sum(nums[:3])

        #特殊情况
        if lenNums == 3:
            return retNum
        if target <= nums[0] and target < retNum:
            return retNum
        if target >= nums[lenNums - 1] and sum(nums[-3:]) <= target:
            return sum(nums[-3:])

        #找到最接近target的值作为遍历范围
        # mid = 0
        # for i in range(lenNums):
        #     mid = i
        #     if nums[i] >= target:
        #         break
        # print('mid',mid)
        #循环的值不会比target大
        for i in range(lenNums):
            # print('i',i)
            val = nums[i]
            l = i + 1
            r = lenNums - 1
            while l < r:
                # print('l',l,'r',r)
                if abs(val + nums[l] + nums[r] - target) < abs(retNum - target):
                    retNum = val + nums[l] + nums[r]
                    if retNum == target:
                        return retNum
                    elif retNum < target:
                        l += 1
                    else:
                        r -= 1
                elif val + nums[l] + nums[r] > target:
                    r -= 1
                else:
                    l += 1
        return retNum