zoukankan      html  css  js  c++  java
  • LeetCode Notes_#16 3Sum Cloest

    LeetCode Notes_#16 3Sum Cloest

    Contents

    题目

    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.

    Example:

    Given array nums = [-1, 2, 1, -4], and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

    思路和解答

    思路

    感觉可以用3Sum类似的思路来做。

    • 排序
    • 固定一个数,然后用左右指针遍历之后的其他的数,用一个list记录sum与target的差值,找出绝对值最小的min,然后返回target+min
      • 问题在于:如何移动左右指针?一样的,大了就变小,小了就变大(为什么不会漏掉一些情况呢?)

    解答

    class Solution(object):
        def threeSumClosest(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            nums.sort()
            result=nums[0]+nums[1]+nums[2]
            for i in range(0,len(nums)-2):
                l=i+1
                r=len(nums)-1
                while(l<r):
                    sum=nums[i]+nums[l]+nums[r]
                    if sum==target:
                        return sum
                    if abs(sum-target)<abs(result-target):
                        result=sum
                    if sum<target:
                        l+=1
                    else:
                        r-=1
            return result
    

    其实还是借鉴之前3sum的方法,几乎都是一样的

  • 相关阅读:
    pyinstaller guid
    python filter()和map()函数
    python eval()
    day6
    repr()函数是什么鬼?
    fibonacci_question
    冒泡算法
    python 函数
    day4作业
    NOIp 2013 #1 积木大赛 Label:有趣的模拟
  • 原文地址:https://www.cnblogs.com/Howfars/p/9960149.html
Copyright © 2011-2022 走看看