题目来源:https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/
给定一个数组 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]。不能使用除法。
示例:
输入: [1,2,3,4,5]
输出: [120,60,40,30,24]
思路:
B[i]表示除去A[i]以外所有数相乘的结果,也就是说以A[i]作为分界线。
那么可以分两部分,第一部分计算A[i]左边的乘积,第二部分计算A[i]右边的乘积。
- left, right = [1] * n, [1] * n
- left[i] = left[i-1] * a[i-1],1<=i<n
- right[i] = right[i+1] * a[i+1],n-2>=i >=0
class Solution(object):
def constructArr(self, a):
"""
:type a: List[int]
:rtype: List[int]
"""
n = len(a)
left = [1] * n
right = [1] * n
res = []
for i in range(1, n):
left[i] = left[i-1] * a[i-1]
for i in range(n-2, -1, -1):
right[i] = right[i+1] * a[i+1]
for i in range(n):
res.append(left[i] * right[i])
return res