[LeetCode] 238. Product of Array Except Self

坑真的很多,首先要处理全零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

posted @ 2024-07-07 19:31  夜歌乘年少  阅读(2)  评论(0编辑  收藏  举报