Product of Array Except Self

Product of Array Except Self

1.without division

2.O(n)

3.with constant space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ret = []
n = len(nums)
tmp = 1
for i in range(0, n):
ret.append(tmp)
tmp *= nums[i]
tmp = 1
for i in range(n - 1, -1, -1):
ret[i] *= tmp
tmp *= nums[i]
return ret

result

1
2
In [53]: s = Solution(); s.productExceptSelf([1, 2, 3, 4])
Out[53]: [24, 12, 8, 6]

leet code