[LeetCode] 238. 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.)

这道题要求是时间复杂度是O(N), 除了结果空间复杂度是O(1)。比较直观的想法肯定是要求所有值的积再除以当前数。但是题目要求不能用除法,所以我们就需要另辟蹊径。我的一个想法是用bit operation来代替除法,结果发现这个比较难,没写出来。看答案以后发现可以这样拆分,其实要求除它自己以外的乘积,只需要求出它之前的乘积和它之后的乘积,两个相乘即可。所以我们可以用两个数组,一个记录对应位置上元素之前的累计的乘积,一个记录对应位置上元素之后的累计的乘积。然后把两个集合相乘就可以。但是题目又要求优化空间复杂度。那么我们可以看出再第二个集合,其实可以用一个数值不停的记录之前的乘积,然后直接和第一个值合并求出结果即可。

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        if not nums: return nums
        
        res = [1]
        for i in range(1, len(nums)):
            res.append(res[i-1] * nums[i-1])
        
        right = 1
        for i in range(len(nums)-1, -1, -1):
            res[i] *= right 
            right *= nums[i]
            
        return res

posted on 2020-04-16 07:53  codingEskimo  阅读(106)  评论(0编辑  收藏  举报

导航