本文完整拆解 LeetCode 3 3Sum 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 3Sum 一次弄懂。
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, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter.
Example 2:
Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0.
Example 3:
Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0.
Constraints:
3 <= nums.length <= 3000-105 <= nums[i] <= 105
Python
class Solution:
def twoSum(self, nums: List[int], i: int, result: List[List[int]]):
low = i + 1
hight = len(nums) - 1
while (low < hight):
sum = nums[i] + nums[low] + nums[hight]
if sum < 0:
low += 1
elif sum > 0:
hight -= 1
else:
result.append([nums[i], nums[low], nums[hight]])
low += 1
hight -= 1
while low < hight and nums[low] == nums[low - 1]:
low += 1
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
nums.sort()
for i, item in enumerate(nums):
if item > 0:
break
if item != nums[i-1] or i == 0:
self.twoSum(nums, i, result)
return result
3Sum 解題思路
三數之和的核心是「先排序,再把三數問題降維成兩數問題」。排序之後,固定第一個數,剩下的就變成在有序區間裡找兩數和等於特定值——這正是雙指針最擅長的場景:和太大就把右指針往左收,太小就把左指針往右推,每一步都是可靠的單調決策。
3Sum 演算法步驟
- 將陣列由小到大排序,後續的夾逼與去重都依賴這個順序。
- 外層固定索引 i 當第一個數;若 nums[i] 大於 0 可提前結束,因為之後全是正數不可能加總為零。
- 若 i 大於 0 且 nums[i] 與 nums[i-1] 相同就跳過,避免輸出重複組合。
- 在 i+1 到 n-1 的區間用左右指針夾逼,和為零時記錄答案,並同時移動兩端且跳過連續相同的值。
3Sum 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(n²) |
| 空間複雜度 | O(1) |
排序需要 O(n log n),外層迴圈跑 n 次、每次內層雙指針最多線性掃描一遍,因此整體由 O(n²) 主導。除了排序本身可能用到的遞迴堆疊外沒有額外資料結構,空間視為 O(1)(不計算輸出陣列)。
3Sum 的邊界情況與常見錯誤
- 陣列長度小於 3 時直接回傳空陣列。
- 全部都是 0 的輸入必須只輸出一組 [0,0,0],去重邏輯要能處理。
- 找到答案之後也要跳過連續重複值,只在移動前去重會漏掉。
- 部分語言的整數相加可能溢位,必要時改用更大的型別。
3Sum 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 三層暴力迴圈 | O(n³) | O(1) | 最直覺,但 n 稍大就會 TLE |
| 固定兩數 + 雜湊表找第三數 | O(n²) | O(n) | 省掉排序,但去重相當麻煩且常數較大 |
| 排序 + 雙指針 | O(n²) | O(1) | 本文採用,去重自然、空間最省 |
