Leetcode 238. Product of Array Except Self

Question

Solution

因为不能用除法,所以只能考虑乘法。考虑两次乘法,第一次从左乘到右,第二次从右乘到左。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
p = 1
output = []
for i in range(n):
output.append(p)
p *= nums[i]
# 对每个元素乘以其之前的元素,对于第一个元素相当于没乘(只乘以了1)。
p = 1
for i in range(n-1, -1, -1):
output[i] *= p
p *= nums[i]
# 从右到左,每个元素乘以其右边的所有元素,对于最后一个元素相当于没有乘。
return output