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的方法,几乎都是一样的

原文地址:https://www.cnblogs.com/Howfars/p/9960149.html