My Python naive solution


  • 0

    The basic idea is that ans[i] should be equal to the product of (0~i-1) times the product of (i+1~end)

    class Solution(object):
        def productExceptSelf(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            if not nums:
                return []
            length = len(nums)
            prosofar, profrom = [0 for i in xrange(length)], [0 for i in xrange(length)]
            for i in xrange(length):
                prosofar[i] = nums[i] * prosofar[i - 1] if i != 0 else nums[i] 
            for i in xrange(length-1, -1, -1):
                profrom[i] = profrom[i + 1] * nums[i] if i != length - 1 else nums[i]
            prosofar, profrom = [1] + prosofar + [1], [1] + profrom + [1]
            ans = []
            for i in xrange(1, length+1):
                ans.append(prosofar[i - 1] * profrom[i + 1])
            return ans
                
    

Log in to reply
 

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