Do the same way as 3 Sum


  • 0
    class Solution(object):
        def threeSumClosest(self, nums, target):
            nums.sort()
            i, ans = 0, 0xffffffff
            while i < len(nums) - 2:
                left, right = i + 1, len(nums) - 1
                while left < right:
                    tmp = nums[i] + nums[left] + nums[right]
                    ans = ans if abs(ans - target) < abs(tmp - target) else tmp
                    if tmp > target:
                        right -= 1
                    elif tmp < target:
                        left += 1
                    else:
                        return tmp
                i += 1
            return ans
    

Log in to reply
 

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