安静如鸡

  • 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

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

最新 热点 随机
最新 热点 随机
122. Best Time to Buy and Sell Stock II 16. 3Sum Closest 259. 3Sum Smaller 17. Letter Combinations of a Phone Number Unity中的相机投影矩阵以及推导 15. 3Sum
122. Best Time to Buy and Sell Stock II
git status 日文文件名乱码 日本人怎么设计的网站? 122. Best Time to Buy and Sell Stock II 【Unity小贴士】如何分析Crash Dmp 被双城之战的剧透搞到心神不宁 Ubuntu 18 → 22 升级实录

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

Theme Kratos Made By Seaton Jiang