Leetcode 16: 3Sum Closest

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        res=0
        temp=float('inf')
        nums.sort()
        n=len(nums)
        #[-3, 0, 1, 2]
        for i in range(n-2):
            l, r= i+1, n-1
            while l<r:
                s=nums[i]+nums[l]+nums[r]
                if s==target:
                    return s
                if s<target:
                    if temp>abs(target-s):
                        temp=abs(target-s)
                        res=s; l+=1
                    elif temp<=abs(target-s):
                        l+=1
                    while l<r and nums[l-1]==nums[l]:
                        l+=1
                elif s>target:
                    if temp>abs(target-s):
                        temp=abs(target-s)
                        res=s; r-=1
                    elif temp<=abs(target-s):
                        r-=1
                    while l<r and nums[r]==nums[r+1]:
                        r-=1
        return res

 

上一篇:Leetcode 15: 3Sum


下一篇:16. 3Sum Closest (M)