首页 > 其他 > 详细

238. Product of Array Except Self

时间:2020-07-22 13:47:04      阅读:44      评论:0      收藏:0      [点我收藏+]

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

 

238. Product of Array Except Self

原文:https://www.cnblogs.com/whatyouthink/p/13359833.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!