Leetcode算法——16、最接近的三数之和

本文介绍了一种算法,用于在给定数组中寻找三个数,使它们的和最接近给定的目标值。该算法使用了外层循环加首尾指针的方法,通过记录与目标的差值来确定最接近的三数之和。

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

题目

给定一个数组,包含n个整数,以及一个目标整数。要求在数组中找到三个数,使得这三个数之和最接近目标整数,返回三数之和。

假设每个输入都只有一个答案。

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.

示例:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

思路

参考Leetcode算法——15、三数求和,也是外层循环+首尾指针,只不过本题需要记录每一次与target的差值,并将最小差值存储下来。最后通过最小差值和target,便可以反推出三数之和。

python实现

def threeSumClosest(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    与第15题思想类似,也是外层循环+首尾指针,只不过本题需要记录每一次与target的差值,并将最小差值存储下来。
    
    """
    
    if len(nums) < 3:
        return []
    
    nums.sort()
    min_diff = sum(nums[:3]) - target
    for i in range(len(nums) - 2):
        if i > 0 and nums[i-1] == nums[i]: # 避免i重复
            continue
        l, r = i + 1, len(nums) - 1 
        while l < r:
            diff = nums[i] + nums[l] + nums[r] - target
            if diff == 0: # 正好等于target,直接返回,肯定是最小差值
                return target
            else:
                if abs(diff) < abs(min_diff): # 更新最小差值
                    min_diff = diff
                # 根据diff大小判断哪个指针需要移动
                if diff < 0: # 三数之和不够则往右走
                    l += 1
                else: # 三数之和过大则往左走
                    r -= 1
    return min_diff + target

if '__main__' == __name__:
    nums = [-1, 0, 1, 1, 55]
    target = 3
    print(threeSumClosest(nums, target))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值