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

3Sum Smaller 解題教學示意圖|LeetCode 259

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

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


You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete at most two transactions.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 105

Python

				
					# time complexity: O(n^2)
# space completity: O(1)
from typing import List


class Solution:
    def threeSumSmaller(self, nums: List[int], target: int) -> int:
        result = 0
        nums.sort()
        for i in range(len(nums) - 1):
            result += self.twoSumSmaller(nums, i + 1, target - nums[i])
        return result

    def twoSumSmaller(self, nums: List[int], startIdx: int, target: int) -> int:
        left = startIdx
        right = len(nums) - 1
        result = 0
        while left < right:
            if nums[left] + nums[right] < target:
                result += right - left
                left += 1
            else:
                right -= 1
        return result


nums = [-2, 0, 1, 3]
target = 2
print(Solution().threeSumSmaller(nums, target))
				
			

3Sum Smaller 解題思路

這題要數「和小於 target 的三元組個數」,而不是列出它們。排序後固定第一個數,剩下用雙指針:若 nums[i] + nums[left] + nums[right] 小於 target,代表「left 與 right 之間的所有右端點」都成立,可以一次加上 right – left 個組合,不必逐一列舉。

3Sum Smaller 演算法步驟

  1. 將陣列排序,初始化 count = 0。
  2. 固定索引 i,令 left = i+1、right = n-1。
  3. 若三數之和小於 target,則 count += (right – left),並把 left 右移。
  4. 否則把 right 左移,重複直到 left 與 right 相遇。

3Sum Smaller 複雜度分析

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

排序 O(n log n),外層 n 次搭配內層線性夾逼,整體 O(n²)。只用常數個變數,空間 O(1)。一次加 right – left 是本解法的關鍵,省掉了第三層迴圈。

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

  • 陣列長度小於 3 時答案為 0。
  • 這題不需要去重,因為算的是索引組合數而非數值組合。
  • count 可能很大,注意整數範圍。
  • 嚴格小於與小於等於的差別會影響指針移動條件,依題意調整。

3Sum Smaller 其他解法比較

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