LeetCode Notes_#16 3Sum Cloest

本文详细解析了LeetCode上的经典问题——寻找数组中三个数之和最接近目标值的算法。通过借鉴3Sum的解题思路,采用排序和双指针技术,实现高效求解。文章提供了Python代码示例,深入浅出地解释了算法背后的逻辑。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值