本文完整拆解 LeetCode 238 Product of Array Except Self 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Product of Array Except Self 一次弄懂。
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 an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4] Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]
Constraints:
2 <= nums.length <= 105-30 <= nums[i] <= 30- The product of any prefix or suffix of
numsis guaranteed to fit in a 32-bit integer.
Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
Python
# time complexity: O(n)
# space complexity: O(n)
from typing import List
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = len(nums)
lList, rList = [1]*length, [1]*length
lList[0], rList[length - 1] = 1, 1
for i in range(1, length):
lList[i] = lList[i-1] * nums[i-1]
for i in reversed(range(length-1)):
rList[i] = rList[i+1] * nums[i+1]
for i in range(length):
lList[i] *= rList[i]
return lList
Arrays = [-1, 1, 0, -3, 3]
print(Solution().productExceptSelf(Arrays))
Product of Array Except Self 解題思路
題目禁止用除法,又要求線性時間,答案是把「除了自己以外的乘積」拆成左半邊乘積乘上右半邊乘積。先從左往右累積每個位置的左側乘積,再從右往左把右側乘積乘回去,兩趟掃描就能完成,而且輸出陣列本身就能當暫存區。
Product of Array Except Self 演算法步驟
- 建立答案陣列 res,res[0] 設為 1。
- 由左往右掃描,令 res[i] = res[i-1] * nums[i-1],此時 res[i] 是 i 左側所有數的乘積。
- 用一個變數 right 初始化為 1,由右往左掃描。
- 每一步令 res[i] = res[i] * right,再更新 right = right * nums[i]。
Product of Array Except Self 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(n) |
| 空間複雜度 | O(1) |
兩趟線性掃描,時間 O(n)。除了題目要求的輸出陣列之外只用一個 right 變數,額外空間是 O(1)——這正是這題的進階要求。
Product of Array Except Self 的邊界情況與常見錯誤
- 陣列含有 0 時這個解法仍正確,不需要特判幾個 0。
- 不可以先算總乘積再除以自己,除了題目禁止之外,遇到 0 也會出錯。
- 整數乘積容易溢位,必要時改用 64 位元型別。
- 長度為 1 的陣列依題意通常不會出現,但實作上要避免存取 nums[-1]。
Product of Array Except Self 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 雙層迴圈逐一相乘 | O(n²) | O(1) | 最直覺,資料量大就超時 |
| 總乘積除以自身(需特判 0) | O(n) | O(1) | 題目禁止,且要處理 0 的數量 |
| 左右前綴乘積,輸出陣列當暫存 | O(n) | O(1) | 本文採用 |
