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

Example:

Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It’s guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        re = [1 for _ in range(len(nums))]
        forward = [1 for _ in range(len(nums))]
        backwrad = [1 for _ in range(len(nums))]
        forward[0] = 1
        backward[len(nums)-1] = 1
        for i in range(1,len(nums)):
            forward[i] = forward[i-1] * nums[i-1]
        for i in range(len(nums)-2,-1,-1):
            backward[i] = backward[i+1] * nums[i+1]
        for i in range(0,len(nums)):
            re[i] = forward[i] * backward[i]
        return re

Product of Array Except Self


请多多指教。

文章标题:Product of Array Except Self

本文作者:顺强

发布时间:2020-04-16, 23:59:00

原始链接:http://shunqiang.ml/leetcode-product-nums/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏