Share my python solution


  • 0
    T
    class Solution(object):
        def threeSumClosest(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            if len(nums) < 3:
                return -1
    
            nums.sort()
            mn = nums[0] + nums[1] + nums[2]
            if mn > target:
                return mn
            mx = nums[-1] + nums[-2] + nums[-3]
            if mx < target:
                return mx
    
            if target - mn < mx - target:
                closest = mn
                diff = target - mn
            else:
                closest = mx
                diff = mx - target
                
            for i in range(len(nums) - 2):
                lf, rg = i + 1, len(nums) - 1
                while lf < rg:
                    sm = nums[i] + nums[lf] + nums[rg]
                    if abs(sm - target) < diff:
                        closest = sm
                        diff = abs(sm - target)
    
                    if sm == target:
                        return sm
                    elif sm < target:
                        if nums[i] + 2*nums[rg] < target:
                            break
                        lf += 1
                    else:
                        if nums[i] + 2*nums[lf] > target:
                            break
                        rg -= 1
            return closest
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.