238. Product of Array Except Self

Given an array nums of n integers where n > 1, return an array outputsuch that output[i] is equal to the product of all the elements of numsexcept nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

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

解题要点:

新增两个新list分别为left和right,其中left从1开始,后面依次为left[i] = left[i-1] * nums[i-1];反之,right则从后往前right[i] = right[i+1] * nums[i+1]。最后的返回值为left[i] * right[i]。

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        
        res = [0] * n
        left = [0] * n
        right = [0] * n
        
        left[0] = 1
        right[-1] = 1
        
        for i in range(1, n):
            left[i] = left[i - 1] * nums[i - 1]
            right[n - i - 1] = right[n - i] * nums[n - i]

        for j in range(0, n):
            res[j] = left[j] * right[j]
            
        return res

Last updated

Was this helpful?