思路一:
两重循环,在遍历数组A的时候,A[i]赋值为1,计算B[i]。时间复杂度为O(N2)
# -*- coding:utf-8 -*-
class Solution:
def multiply(self, A):
# write code here
result = []
for i in range(len(A)):
temp = 1
for j in range(len(A)):
if i != j:
temp *= A[j]
result.append(temp)
return result
思路二:
时间复杂度为O(N)
可以把B[i]=A[0]An[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]分为两部分的乘积。效果相当于是个对角矩阵。
# -*- coding:utf-8 -*-
import copy
class Solution:
def multiply(self, A):
# write code here
if len(A) == 0:
return []
result = copy.copy(A)
result[0] = 1
for i in range(1,len(A)):
result[i] = result[i-1] * A[i-1]
temp = 1
#反向遍历相乘
for j in range(len(A)-2,-1,-1):
temp *= A[j+1]
result[j] *= temp
return result