繁体   English   中英

Python 中 prod() 的数学时间复杂度是多少

[英]What's the time complexity of prod() in math in Python

概括)

  1. math.prod()的时间复杂度是多少
  2. 如何改进此代码以获得通过

细节)

目前正在研究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)。

请告诉我这里的时间复杂度以及一些通过此问题的提示。

  1. 几乎肯定是 O(n); 追加是 O(1),但在许多调用中摊销。 这取决于实现,但一些调用将不得不重新分配更大的 memory 并将目前存在的所有内容复制到新空间中。

  2. 这些挑战的重点是让你思考你可以采取的更好的方法,并练习学习认识到你如何看待通常的方法以及将你带到更好的方法的路径,以便你能够做到这一点在一个不平凡的问题上更容易思考。 也就是说:您可以只计算一次完整的数组乘积,然后将该乘积除以每个数组元素以产生结果。 使用生成器或列表推导。

首先计算当前元素之前所有元素的前缀积。 然后计算该元素后所有元素的乘积。 最后 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM