iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
自我挑戰組

leetcode系列 第 16

leetcode 16. 3Sum Closest

  • 分享至 

  • xImage
  •  

題目:
Given an integer array nums of length n 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.

nums給定一個長度為 的整數數組n和一個整數target,找出 中的三個整數,nums使得它們的和最接近target。

傳回三個整數的和。

您可以假設每個輸入只有一個解。
https://ithelp.ithome.com.tw/upload/images/20250930/20169340eASLqa5ot6.png
解題思路

這題和 15. 3Sum 很像,只是從「找到和為 0 的三元組」改成「找到最接近 target 的三元組和」。

排序 (Sorting)

先對陣列排序,方便使用雙指針。

固定一個數 + 雙指針

外層:固定一個數 nums[i]。

內層:雙指針 left = i+1, right = n-1。

計算總和 sum = nums[i] + nums[left] + nums[right]。

更新最接近的答案:如果 |sum - target| < |closest - target| → 更新。

移動指針

如果 sum < target,代表和太小 → left++。

如果 sum > target,代表和太大 → right--。

如果剛好相等 sum == target,直接回傳 target,因為不可能更接近。


上一篇
leetcode 15. 3Sum
系列文
leetcode16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言