150強訪談簡單

除自身之外的數組的乘積

「自體之外的陣列的乘積」問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個整數陣列 nums,傳回一個陣列 answer,使得 answer[i] 等於 nums 中除 nums[i] 之外的所有元素的乘積。

nums 的任何前綴或後綴的乘積保證適合 32 位元整數。

您必須編寫一個在 O(n) 時間內運作且不使用除法運算的演算法。

寫一個函數 productExceptSelf(nums: List[int]) -> List[int]

約束條件
  • 2 <= len(nums) <= 10^5
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums fits in a 32-bit integer

範例

Example 1
Input
nums = [1, 2, 3, 4]
Output
[24, 12, 8, 6]
Explanation

answer[0] = 2*3*4 = 24, answer[1] = 1*3*4 = 12, answer[2] = 1*2*4 = 8, answer[3] = 1*2*3 = 6.

Example 2
Input
nums = [-1, 1, 0, -3, 3]
Output
[0, 0, 9, 0, 0]
Explanation

Any product that includes the 0 at index 2 becomes 0. answer[2] = (-1)*1*(-3)*3 = 9.

Need a Hint?
考慮使用數組和哈希特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。