其他分享
首页 > 其他分享> > Leetcode 16: 3Sum Closest

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

 

标签:Closest,temp,nums,3Sum,res,int,abs,Leetcode,target
来源: https://blog.csdn.net/qq_39012149/article/details/96187995