Python: A faster solution if there are zeros in a long list of numbers


  • 0
    B

    class Solution(object):
    def productExceptSelf(self, nums):
    product = 1
    zeros_index = -1
    output = [0] * len(nums)
    for i in range(len(nums)):
    if nums[i] == 0:
    if zeros_index == -1:
    zeros_index = i
    else:
    return [0] * len(nums)
    else:
    product *= nums[i]
    if zeros_index != -1:
    output[zeros_index] = product
    else:
    for i in range(len(nums)):
    output[i] = product / nums[i]
    return output


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.