16. 3Sum Closest- Medium - Squeeze method (the sum, to find the closest to the target value) after sorting

 

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        if len(nums)<=2:
            return None
        if len(nums)==3:
            return sum(nums)
        
        small=float('-inf')
        large=float('inf')
        n=len(nums)
        res=0
        nums=sorted(nums)  ##排序之后用夹逼的方法
        
        for i in range(n-2):
            if i>0 and nums[i]==nums[i-1]:
                continue
            j=i+1
            k=n-1
            
            while j<k:
                tmp=nums[i]+nums[j]+nums[k]
                if tmp==target:
                    return target
                elif tmp <target:
                    small=max(small,tmp)  ##
                    j+=1
                else:
                    large=min(large,tmp)  ##
                    k-=1
        if abs(small-target)<abs(large-target):  ##取绝对值最小的
            res=small
        else:
            res=large
        return res
            

Published 170 original articles · won praise 90 · views 6389

Guess you like

Origin blog.csdn.net/weixin_45405128/article/details/104450373