[LeetCode] 238. Product of Array Except Self

夜歌乘年少發表於2024-07-07

坑真的很多,首先要處理全零reduce沒有值typeerror的問題。

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        total=reduce(mul, nums)
        ret =[]

        if total == 0:
            try:
                total = reduce(mul, [x for x in nums if x != 0]) 
            except TypeError:
                #default value for all element is 0
                total = 0
            ret = [total if x==0 else 0 for x in nums]
        else:
            ret = [total// x for x in nums]
        return ret

然後發現如果零大於1個,必然返回全零list,改造一下。

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        # 0>1 return 0
        if nums.count(0) > 1:
            return [0 for x in nums]
        #else
        total=reduce(mul, nums)
        ret =[]

        if total == 0:
            total = reduce(mul, [x for x in nums if x != 0])
            ret = [total if x==0 else 0 for x in nums]
        else:
            ret = [total// x for x in nums]
        return ret

錯了兩次,不過結果還不錯

image


好吧,不讓用除法,改成先算左側乘積再算右側乘積,最後相乘。
切片+列表推倒式會超時。

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        # 0>1 return 0
        if nums.count(0) > 1:
            return [0 for x in nums]
        #else
        n = len(nums)
        ret =[1]* n
        left_mul = 1
        right_mul = 1

        for i, element in enumerate(nums):
            ret[i] *= left_mul  #calcu the ret[i]
            left_mul *= element #update left_mul with element

        for i in range(n - 1, -1, -1):
            ret[i] *= right_mul
            right_mul *= nums[i]
        return ret

image

相關文章