zoukankan      html  css  js  c++  java
  • 16. 最接近的三数之和

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

    示例:

    输入:nums = [-1,2,1,-4], target = 1
    输出:2
    解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
     

    提示:

    3 <= nums.length <= 10^3
    -10^3 <= nums[i] <= 10^3
    -10^4 <= target <= 10^4

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/3sum-closest

    class Solution:
        def threeSumClosest(self, nums: List[int], target: int) -> int:
            nums.sort()
            n=len(nums)
            res=float('inf')
    
            def update(cur):
                nonlocal res
                if abs(cur-target)<abs(res-target):
                    res=cur
            
            for i in range(n):
                if i>0 and nums[i]==nums[i-1]:
                    continue
                j,k=i+1,n-1
                while j<k:
                    s=nums[i]+nums[j]+nums[k]
                    if s==target:return target
                    update(s)
                    if s<target:
                        jj=j+1
                        while jj<k and nums[jj]==nums[j]:
                            jj+=1
                        j=jj
                    else:
                        kk=k-1
                        while j<kk and nums[kk]==nums[k]:
                            kk-=1
                        k=kk
            
            return res
                
  • 相关阅读:
    mysql把查询结果集插入到表理
    js遍历json数据
    php事务回滚
    win10定时执行php脚本
    php输出json的内容
    图像的几个基本概念
    linux系统编程之I/O内核数据结构
    linux系统编程之错误处理
    深拷贝和浅拷贝
    mysql用户的创建
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13704542.html
Copyright © 2011-2022 走看看