安静如鸡

  • Home
  • About Me
  • Contact Me
  • 东京女子篮球活动记录
一个博客
  1. 首页
  2. Tech
  3. Leetcode
  4. 正文

16. 3Sum Closest

2026-08-31 0人点赞 0条评论

Given an integer array nums of length n and an integer target, find three integers at distinct indices 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 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Code language: HTTP (http)

Example 2:

Input: nums = [0,0,0], target = 1
Output: 0
Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
Code language: HTTP (http)

详细见259. 3Sum Smaller

基本上是同一个思路,只是closet主要是要计算出一个最接近的值,还有一个比较难想通的地方是,双指针怎么移动和需要return的result没关系,需要单独移动。


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        diff = float("inf")
        res = 0
        nums.sort()
        for i, n in enumerate(nums):
            t = target - n

            left = i + 1
            right = len(nums) -1 
            while left < right:
                curr = nums[left] + nums[right]

                if abs(nums[left] + nums[right] - t) < diff:
                    diff = abs(nums[left] + nums[right] - t)
                    res = nums[left] + nums[right] + n
               
                # 决定双指针怎么移动
                if curr < t:
                    left += 1
                elif curr > t:
                    right -= 1
                else:
                    return res

        return res
Python
标签: 暂无
最后更新:2026-08-31

Ellison

什么都懂点,什么都不精。属于混吃等死,享受生活,过一天算一天的享乐主义。喜欢电影,阅读,以及游戏和美食。

点赞
< 上一篇

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

Ellison

什么都懂点,什么都不精。属于混吃等死,享受生活,过一天算一天的享乐主义。喜欢电影,阅读,以及游戏和美食。

最新 热点 随机
最新 热点 随机
16. 3Sum Closest 259. 3Sum Smaller 17. Letter Combinations of a Phone Number Unity中的相机投影矩阵以及推导 15. 3Sum 628. Maximum Product of Three Numbers
Unity中的相机投影矩阵以及推导17. Letter Combinations of a Phone Number259. 3Sum Smaller16. 3Sum Closest
Wordpress固定连接404问题解决 16. 3Sum Closest Fix You (五) 【Unity小贴士】取得一个Texture的四个顶点在WorldSpace的Position Ubuntu 18 → 22 升级实录 Apple Storeにアプリ認証について

COPYRIGHT © 2024 安静如鸡. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang