Leetcode 每日一题 最接近的三数和

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        
        nums.sort()
        res = 99999

        for i in range(len(nums)-2):
            
            t1 = i+1
            t2 = len(nums)-1
            #print(i,t1,t2)
            while t1<t2:
               # print(target-(nums[i]+nums[t1]+nums[t2]))
                if abs(target-(nums[i]+nums[t1]+nums[t2]))<res:

                    s = nums[i]+nums[t1]+nums[t2]
                    res = abs(target-(nums[i]+nums[t1]+nums[t2]))
                if nums[i]+nums[t1]+nums[t2]<=target:
                    t1+=1
                elif nums[i]+nums[t1]+nums[t2]>target:
                    t2-=1
        return s
            

  

猜你喜欢

转载自www.cnblogs.com/SuckChen/p/13190714.html