【LEETCODE】238-Product of Array Except Self

1294 ワード

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
タイトル:
n個の整数、n>1を有する配列を与え、
nums[i]以外の数の積でoutput[i]を返す配列
除算divisionを用いず,時間複雑度はO(n)である.
定数レベルの空間複雑さをどうするかを考える
参照先:
http://www.tuicool.com/articles/IbUvmeJ
考え方:
全部で2回遍歴しましたが、
numsを1回遍歴しoutput[i]のleftの蓄積を生成する
numsを1回遍歴しoutput[i]のrightの蓄積を生成する
class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        output=[1]*len(nums)
        
        left=1
        
        for i in range(len(nums)-1):                    #  left
            left*=nums[i]
            output[i+1]*=left
        
        right=1
        
        for i in range(len(nums)-1,0,-1):               #   right
            right*=nums[i]
            output[i-1]*=right
        
        return output