16. 3Sum Closest

本文探讨了在给定数组中寻找三个数,使它们的和最接近目标值的问题。通过排序和双指针技巧,实现了高效求解。代码示例采用Python实现,详细解释了解题思路。

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

题目:

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).
题意: 给出一个数组和一个目标值,在该数组中找到三个数,使之和与目标值最为接近,假设唯一存在最为接近的值。
思路: 此题解法核心思路与上一题(15题)几乎一致,使用三个指针即可,区别是上一题要求找出数组中三个数值和与target相等的所有不重复数组(需要去重),就是要求三个指针对应的数值和与target相等,而这一题要求和与target最为接近,只需返回最为最终三个数的和即可。使用绝对值比较,保留绝对值最小的那三个数的和,时间复杂度为 O ( n ) O(n) O(n)
代码仅供参考:

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums = sorted(nums)
        n = len(nums)
        Sum = nums[0] + nums[1] + nums[2]
        for i in range(n-2):
            re_nums = nums[i+1:]
            j = 0
            k = len(re_nums) - 1
            while j < k:
                result = nums[i] + re_nums[j] + re_nums[k]
                if abs(result-target) < abs(Sum - target):
                    Sum = result
                if result < target:
                    j += 1
                elif result > target:
                    k -= 1
                else:
                    return result
        return Sum
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值