LeetCode----Product of Array Except Self

Product of Array Except Self

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

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

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

分析:

給定一個整型數組,返回一個結果數組,要求返回的數組的第i項表示原數組中除第i項外所有項的乘積,不使用除法,O(n)時間。

假定有數組[a1, a2, ..., ax, c, b1, b2, ... by],那麼c的位置返回的應該是a1*a2*...*ax * b1*b2*... *by。

一個簡單的思路:使用數組ArrayA存儲由前往後,每一項存儲到該項所有元素的乘積,使用數組ArrayB存儲由後往前,每一項存儲該項後面所有元素的乘積,最後將兩個數組對應項相乘,所得的乘積數組即爲結果數組。


代碼:

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        nLen = len(nums)
        ans = [0] * nLen
        ans[0] = 1
        step = range(nLen)
        # 從前往後,該論循環結束後,ans數組的每一項存儲該項前面所有元素的乘積
        for i in step[1:]:
            ans[i] = ans[i - 1] * nums[i - 1]
        # 由後往前,nums數組的每一項存儲該項及後面所有元素的乘積
        for j in step[::-1][1:]:
            ans[j] = ans[j] * nums[j + 1]
            nums[j] = nums[j] * nums[j + 1]
        return ans
發佈了143 篇原創文章 · 獲贊 59 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章