美文网首页
238. Product of Array Except Sel

238. Product of Array Except Sel

作者: April63 | 来源:发表于2018-05-16 14:31 被阅读0次

    这一题的思路是,首先扫描一遍数组,在这里需要完成两件事,第一件事计算乘积,第二件事计算0的个数,如果当前的位置上数字不为零,需要做乘法,如果当前位置上数字为零,不做乘法,count+1, 如果此时count为2,说明有两个零,对于数组来说有两个零,最后的输出就都是0,此时可以直接跳出来循环了。代码如下:

    class Solution(object):
        def productExceptSelf(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            if len(nums) < 2:
                return []
            res = [0 for i in range(len(nums))]
            count = 0
            product = 1
            for i in range(len(nums)):
                if nums[i] == 0:
                    count += 1
                    index = i
                    if count == 2:
                        break
                else:
                    product *= nums[i]
            if count == 0:
                for i in range(len(nums)):
                    res[i] = product / nums[i]
            elif count == 1:
                res[index] = product
            return res
    

    相关文章

      网友评论

          本文标题:238. Product of Array Except Sel

          本文链接:https://www.haomeiwen.com/subject/eappdftx.html