解法:先将数组排序,然后依次枚举第一个数,使用双指针法找到另外两个数,使得它们的和最接近 target。

具体来说,我们将数组 nums 排序,然后依次枚举数组中的每个数 nums[i] 作为第一个数,再使用双指针法找到另外两个数,使得它们的和最接近 target。具体来说,我们初始化左指针为 i+1,右指针为 n-1,然后不断地移动左右指针,如果三个数的和与 target 的差更小了,就更新答案。时间复杂度为 O(n^2)。

代码如下:

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        n = len(nums)
        best = float('inf')
        ans = 0
        for i in range(n):
            left = i + 1
            right = n - 1
            while left < right:
                sum = nums[i] + nums[left] + nums[right]
                if abs(sum - target) < abs(best):
                    best = sum - target
                    ans = sum
                if sum < target:
                    left += 1
                else:
                    right -= 1
        return ans
最接近目标值的三个数 - 算法解析与代码实现

原文地址: https://www.cveoy.top/t/topic/mkYn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录