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

解题方法

  • 建立一个array作为result array, result
  • 先从左到右扫一遍,result[i]表示从左边开头到i-1的乘积
  • 再从右到左扫一遍,对于indexi, 用一个right变量来记录从右边到i+1的乘积,因为这里只需要用前一个值,所以不需要再建array
  • 最后得到的resultarray就是结果

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)]
        result[0] = 1

        # 从左到右        
        for i in range(1, length):
            result[i] = result[i-1] * nums[i-1]

        # right 变量记录右边到目前为止的乘积
        right = 1
        # 从右到左
        for i in range(length - 1, -1, -1):
            result[i] *= right
            right *= nums[i]

        return result

Reference