lc238. Product of Array Except Self

155 阅读1分钟
  1. Product of Array Except Self Medium

4927

418

Add to List

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

Accepted 543,421 Submissions 907,267

思路:头尾各遍历一遍,计算left[0...i],right[i...0]的乘积 result数组的每一位为 result[i]=nums[0...i-1]*nums[i+1,len(nums)]

代码:python3

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        res=[1]*len(nums)
        left=1
        right=1
        for i in range(0,len(nums)-1):
            left=left*nums[i]
            res[i+1]=left
        for j in range(len(nums)-1,0,-1):
            right=right*nums[j]
            res[j-1]=res[j-1]*right
        print(res)
        return res

时间复杂度:O(2m) 空间复杂度:O(m)