给定一个数组 A[0, 1,…, n-1],请构建一个数组 B[0, 1,…, n-1],其中 B 中的元素 B[i]=A[0]*A[1]*…*A[i-1]*A[i+1]*…*A[n-1]。要求不能使用除法。
![](https://i-blog.csdnimg.cn/blog_migrate/600e8f63e25b5cb3b522b2148a35cd47.png)
解题思路
# -*- coding:utf-8 -*-
class Solution:
def multiply(self, A):
# write code here
if not A or len(A) < 0:
return 0
length = len(A)
B = [1] * length
# 下三角,从1开始乘的
for i in range(1, length):
B[i] = B[i - 1] * A[i - 1]
# L指代length
# B=[1,A[0],A[0]*A[1],...,A[0]*...*A[L-2]]
# L=5
# B=[1,A[0],A[0]*A[1],A[0]*A[1]*A[2],A[0]*A[1]*A[2]*A[3]]
temp = 1
for i in range(length - 2, -1, -1):
temp = temp * A[i + 1]
B[i] *= temp
return B
# 循环次数 =L-2-(-1)=L+1
# 第1次循环后
# B=[1,A[0],A[0]*A[1],A[0]*A[1]*A[2]*A[4],A[0]*A[1]*A[2]*A[3]] temp=A[4]
# 第2次循环后
# B=[1,A[0],A[0]*A[1]*A[4]*A[3],A[0]*A[1]*A[2]*A[4],A[0]*A[1]*A[2]*A[3]] temp=A[4]*A[3]
# 第3次循环后
# B=[1,A[0]*A[4]*A[3]*A[2],A[0]*A[1]*A[4]*A[3],
# A[0]*A[1]*A[2]*A[4],A[0]*A[1]*A[2]*A[3]] temp=A[4]*A[3]*A[2]
# 第4次循环后
# B=[1*A[4]*A[3]*A[2]*A[1],A[0]*A[4]*A[3]*A[2],A[0]*A[1]*A[4]*A[3],
# A[0]*A[1]*A[2]*A[4],A[0]*A[1]*A[2]*A[3]] temp=A[4]*A[3]*A[2]*A[1]
from functools import reduce
class Solution:
def multiply(self, A):
# write code here
if not A or len(A) < 0:
return 0
length = len(A)
B = [1] * length
for i in range(0, length):
res = A[::1]
res.remove(A[i])
B[i] = reduce(lambda x, y: x * y, res)
# print(B)
return B