zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    学习进度总结表
    关于软件工程的问题
    自我介绍
    web安全
    spring profile
    spring 装配
    python Descriptor (描述符)
    python string intern
    Java 对象内存占用
    java jdb命令详解
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13359833.html
Copyright © 2011-2022 走看看