Product of Array Except Self

题目描述

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.)

解题方法

Two array

两个array leftright, 分别存从左到i,从右到i的乘积(不包括i)

时间复杂度 O(n) 空间复杂度 O(n)

空间复杂度O(n)

作为result的array不算空间,其实可以讲上一个解法中的从左到右,从右到左在同一个array进行

Solution

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if not nums:
            return []

        length = len(nums)
        if length == 1:
            return 0
        result = [0 for i in range(length)]

        #from left to right
        #for first element, to make the value 1 now for easy multiply after
        result[0] = 1
        for i in range(1, length):
            result[i] = result[i-1] * nums[i-1]

        #from right to left
        #cause we cannot use the value already in the array to represent right to i+1
        #so we use a variable to keep the value
        right = 1
        for i in range(length - 1, -1, -1):
            result[i] *= right
            right *= nums[i]

        return result

Reference