Leetcode=最接近的三数之和

本文详细解析了LeetCode上一道经典题目“最接近的三数之和”的解决方案,介绍了通过排序和双指针技巧寻找与目标值最接近的三个数之和的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode=最接近的三数之和

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

解决方法:类似题库14三数之和的方法,先排序,然后遍历数组,找另外两个数left和right,判断三数之和和target的距离,如果小就left++,如果大就right–。

class Solution:
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        length = len(nums)
        min_val = float("inf")
        res = 0
        for i in range(length - 2):
            l = i + 1
            r = length - 1
            while l < r:
                sum_val = nums[i] + nums[l] + nums[r]
                if sum_val - target == 0:
                    return target
                if abs(sum_val - target) < min_val:
                    min_val = abs(nums[i] + nums[l] + nums[r] - target)
                    res = sum_val
                if sum_val > target:
                    r -= 1
                else:
                    l += 1
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值