16. 3Sum Closest Python


  • 0
    L

    class Solution(object):
    def threeSumClosest(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    """
    ans = nums[0] + nums[1] + nums[-1]
    nums = sorted(nums)

        for i in range(len(nums) - 2):
            j = i + 1
            k = len(nums) - 1
            
            while j < k:
                t_sum = nums[i] + nums[j] + nums[k]
                
                if t_sum > target:
                    k -= 1
                else:
                    j += 1
                
                if abs(t_sum - target) < abs(ans - target):
                    ans = t_sum
        
        return ans

Log in to reply
 

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