美文网首页
18 - Hard - Product of Array Exc

18 - Hard - Product of Array Exc

作者: 1f872d1e3817 | 来源:发表于2018-04-24 11:28 被阅读0次

一个长度为 n 的整形数组nums,其中 n > 1,返回一个数组 output ,其中 output[i] 等于nums中除nums[i]以外所有元素的乘积。

不用除法 且在O(n)内解决这个问题。

例如,输入 [1,2,3,4],返回 [24,12,8,6]。

进阶:
你可以在常数空间复杂度内解决这个问题吗?(注意:出于空间复杂度分析的目的,输出数组不被视为额外空间。)

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res,p=[],1
        for i in nums:
            res.append(p)
            p*=i
        p=1
        for i in range(len(nums)-1,-1,-1):
            res[i]*=p
            p*=nums[i]
        return res

相关文章

网友评论

      本文标题:18 - Hard - Product of Array Exc

      本文链接:https://www.haomeiwen.com/subject/jundlftx.html