O(n) time ,O(1) space, python solution.


  • 1
    I

    base idea:

    1. array contians 2 or more zeros. return a zeros array.

    2. array contians 1 zeros. only 1 element is not zero.

    3. array have not zero. use produce_all / nums[i]

    code:

    class Solution:
        # @param {integer[]} nums
        # @return {integer[]}
        def productExceptSelf(self, nums):
            p = 1
            zc = 0
            for x in nums:
                if x == 0:
                    zc += 1
                else:
                    p *= x
            output = []
            for x in nums:
                if zc > 1:
                    output.append(0)
                elif zc == 1:
                    if x == 0:
                        output.append(p)
                    else:
                        output.append(0)
                else:
                    output.append(p/x)
            return output

Log in to reply
 

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