238. Product of Array Except Self

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

给一个数组,对于每个元素i求nums[0:i - 1] * nums[i+1:],如果给额外的空间的话,其实问题就可以转换成维护两个前缀积,从左到右left[n]一个从右到左一个right[n],答案是left[i] * right[i].

现在要求on并且除了答案不开额外的辅助空间。那就先从左到右更新ans[i]表示i之前的所有元素乘积,然后从右往左维护一个right,表示从右往左到i+1的乘积,用right去更新ans,这样就没有额外的两个辅助数组了。

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        ans = [1] * n
        for i in range(1, n, 1):
            ans[i] = ans[i - 1] * nums[i - 1]
        right = 1
        for i in range(n - 2, -1, -1):
            right = right * nums[i + 1]
            ans[i] *= right
        return ans

 

posted @ 2020-07-22 11:52  whatyouthink  阅读(72)  评论(0编辑  收藏  举报