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
            

  

posted @ 2020-06-24 23:46  SuckChen  阅读(118)  评论(0编辑  收藏  举报