1. 程式人生 > 實用技巧 >238. Product of Array Except Self

238. Product of Array Except Self

Given an arraynumsofnintegers wheren> 1, return an arrayoutputsuch thatoutput[i]is equal to the product of all the elements ofnumsexceptnums[i].

給一個數組,對於每個元素i求nums[0:i - 1] * nums[i+1:],如果給額外的空間的話,其實問題就可以轉換成維護兩個字首積,從左到右left[n]一個從右到左一個right[n],答案是left[i] * right[i].

現在要求on並且除了答案不開額外的輔助空間。那就先從左到右更新ans[i]表示i之前的所有元素乘積,然後從右往左維護一個right,表示從右往左到i+1的乘積,用right去更新ans,這樣就沒有額外的兩個輔助陣列了。

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