Fork me on GitHub

Product of Array Except Self

Description

https://leetcode.com/problems/product-of-array-except-self/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if nums is None or len(nums) == 0 or len(nums) == 1:
return []

multi = 1
left = [1 for i in range(len(nums))]
for i in range(1, len(nums)):
multi *= nums[i - 1]
left[i] = multi

multi = 1
right = [1 for i in range(len(nums))]
for j in range(len(nums) - 2, -1, -1):
multi *= nums[j + 1]
right[j] = multi

ret = []
for k in range(len(nums)):
ret.append(left[k] * right[k])

return ret