解法1:直观解法就是用连乘n-1个数字得到B[i],但是这个方法的时间复杂度是O(n*n)。
class Solution:
def multiply(self, A):
# write code here
B = [1 for i in A]
for i in range(len(B)):
for j in A[:i]+A[i+1:]:
B[i] *= j
return B
解法2:可以把B[i]=A[0]A[1]*…*A[i-1]A[i+1]…*A[n-1]。看成A[0]A[1]…*A[i-1]和A[i+1]…A[n-2]*A[n-1]两部分的乘积。即通过A[i]项将B[i]分为两部分的乘积。效果如下图所示:
*不妨设定C[i]=A[0]A[1]…*A[i-1],D[i]=A[i+1]**…*A[n-2]*A[n-1]。C[i]可以用自上而下的顺序计算出来,即C[i]=C[i-1]*A[i-1]。类似的,D[i]可以用自下而上的顺序计算出来,即D[i]=D[i+1]*A[i+1]。
class Solution:
def multiply(self, A):
# write code here
length = len(A)
B = [1 for i in A]
for i in range(1,length):
B[i] = B[i-1]*A[i-1]
temp = 1
i = length-2
while i>= 0:
temp *= A[i+1]
B[i] *= temp
i -= 1
return B