3Sum Closest 解題教學:3 種解法完整比較|LeetCode 16 Best Practice

3Sum Closest 解題教學示意圖|LeetCode 16

本文完整拆解 LeetCode 16 3Sum Closest 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 3Sum Closest 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


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.

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).

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).

Constraints:

  • 3 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
  • -104 <= target <= 104

Python

				
					# time complexity: O(n)
# space complexity: O(n)
from typing import List


class Solution(object):
    def maxProfit(self, prices: List[int]) -&gt; int:
        if len(prices) &lt;= 1:
            return 0

        leftMin = prices[0]
        rightMax = prices[-1]

        length = len(prices)
        leftProfits = [0] * length
        rightProfits = [0] * (length + 1)

        for l in range(1, length):
            leftProfits[l] = max(leftProfits[l - 1], prices[l] - leftMin)
            leftMin = min(leftMin, prices[l])

            r = length - 1 - l
            rightProfits[r] = max(rightProfits[r + 1], rightMax - prices[r])
            rightMax = max(rightMax, prices[r])

        maxProfit = 0
        print(leftProfits)
        print(rightProfits)
        for i in range(0, length):
            maxProfit = max(maxProfit, leftProfits[i] + rightProfits[i + 1])

        return maxProfit


prices = [7, 1, 5, 3, 6, 4]
# leftProfit = [0, 0, 4, 4, 5, 5]
# rightProfit = [5, 5, 3, 3, 0, 0, 0]
print(Solution().maxProfit(prices))
				
			

3Sum Closest 解題思路

和 3Sum 幾乎同一套骨架:排序後固定第一個數,剩下兩個數用雙指針夾逼。差別只在判斷條件——3Sum 找的是「剛好等於 0」,這題找的是「與 target 的距離最小」,所以每一步都要拿目前的和去更新最佳答案,而不是只在相等時才處理。

3Sum Closest 演算法步驟

  1. 將陣列排序,初始化 closest 為前三個數的和。
  2. 固定索引 i,令 left = i+1、right = n-1。
  3. 計算 sum = nums[i] + nums[left] + nums[right],若 |sum – target| 小於目前最佳差距就更新 closest。
  4. sum 小於 target 時 left 右移,大於時 right 左移,等於 target 可直接回傳。

3Sum Closest 複雜度分析

項目複雜度
時間複雜度O(n²)
空間複雜度O(1)

排序 O(n log n),外層 n 次搭配內層線性夾逼,整體 O(n²)。只用常數個變數,空間 O(1)。與 3Sum 的差異只在更新條件,骨架完全共用。

3Sum Closest 的邊界情況與常見錯誤

  • 初始的 closest 不要設成 0,否則 target 為負時會得到錯誤答案。
  • sum 剛好等於 target 時可以立刻回傳,這是最佳解不可能更好。
  • 比較距離要用絕對值,別只比大小。
  • 題目保證恰有一組最接近的答案,不需要處理並列情況。

3Sum Closest 其他解法比較

解法時間空間說明
三層暴力迴圈O(n³)O(1)可讀但會超時
排序 + 二分搜尋第三個數O(n² log n)O(1)比雙指針慢一個 log
排序 + 雙指針O(n²)O(1)本文採用