美文网首页
每天(?)一道LeetCode(3) 3Sum Closest

每天(?)一道LeetCode(3) 3Sum Closest

作者: 失业生1981 | 来源:发表于2019-01-17 21:33 被阅读0次

    Array

    016. 3Sum Closest

    Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
    即:
    给定一个整数数组,和一个整数target,在数组中找出三个元素满足他们之和距离target最近,然后返回这三个元素的和

    Solutions

    3sum那道题本质上是一样的,稍微改下就可以满足要求

    class Solution:
        def threeSumClosest(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            min_num=float('inf')
            nums.sort()
            res=0
            for i in range(len(nums)):
                r,l=i+1,len(nums)-1
                while r<l:
                    s = (nums[i] + nums[l] + nums[r])-target
                    if abs(s)<min_num:
                        min_num=abs(s)
                        res=s+target
                    if s<0:
                        r+=1
                    elif s>0:
                        l-=1
                    else:
                        return target
            return res
    

    相关文章

      网友评论

          本文标题:每天(?)一道LeetCode(3) 3Sum Closest

          本文链接:https://www.haomeiwen.com/subject/ijuwdqtx.html