【Leetcode】238. Product of Array Except Self

原題不讓用除法,也就是不能先把數組中所有元素乘起來然後對單個元素進行除法運算得到結果。
這樣解決思路就是,針對某個值,先遍歷之前的數乘起來,再遍歷之後的數乘起來。兩者想乘就是當前值對應的輸出。Python代碼:

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res = [1] * len(nums)#初始化輸出
        #遍歷之前的數
        for i in range(1,len(nums)):
            res[i] = res[i-1] * nums[i-1]
        
        #遍歷之後的數
        reverse = 1
        for j in range(0,len(nums))[::-1]:
            res[j] = res[j] * reverse
            reverse = reverse * nums[j]
        #輸出
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章