[英]What's the time complexity of prod() in math in Python
概括)
math.prod()
的時間復雜度是多少細節)
目前正在研究Leetcode上的“Product of Array Except Self”
我的第一個代碼是:
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
product_list = []
for index in range(len(nums)):
deleted_value = nums.pop(index)
product_list.append(math.prod(nums))
nums.insert(index, deleted_value)
return product_list
並認為它是動態數組中的“刪除和插入”,導致時間限制出現問題。
因此,我將一些行更正為:
class Solution:
def product_except_self(self, nums):
product_list = []
for index in range(len(nums)):
temp = nums[index]
nums[index] = 1
product_list.append(math.prod(nums))
nums[index] = temp
return product_list
就我而言,“=”和 append 操作的時間復雜度為 O(1),因此認為 math.prod 是這里提出問題的原因,除了“for”是 O(n)。
請告訴我這里的時間復雜度以及一些通過此問題的提示。
幾乎肯定是 O(n); 追加是 O(1),但在許多調用中攤銷。 這取決於實現,但一些調用將不得不重新分配更大的 memory 並將目前存在的所有內容復制到新空間中。
這些挑戰的重點是讓你思考你可以采取的更好的方法,並練習學習認識到你如何看待通常的方法以及將你帶到更好的方法的路徑,以便你能夠做到這一點在一個不平凡的問題上更容易思考。 也就是說:您可以只計算一次完整的數組乘積,然后將該乘積除以每個數組元素以產生結果。 使用生成器或列表推導。
首先計算當前元素之前所有元素的前綴積。 然后計算該元素后所有元素的乘積。 最后 zip 並將它們相乘。
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
i,p,s,t=1,1,1,1
m,k=[1],[1]
n=nums[::-1]
while i<len(nums):
p=p*nums[i-1]
m.append(p)
i+=1
while s<len(n):
t=t*n[s-1]
k.append(t)
s+=1
return [x*y for x,y in zip(m,k[::-1])]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.