编程语言
首页 > 编程语言> > leetcode 剑指 Offer 66. 构建乘积数组 python

leetcode 剑指 Offer 66. 构建乘积数组 python

作者:互联网

题目描述:

 题解:

1.product1初始化为1,用于保存前缀积,product1 = a[0]*a[1]*...*a[i-1] 

2.product2初始化为1,用于保存后缀积,product2 = a[i+1]*a[i+2]*...*a[n-1]

3.先将product1赋值给b[i] 其中b[0]=1,的到前缀积,然后再将product2中的后缀积和b[i]相乘。

class Solution(object):
    def constructArr(self, a):
        n = len(a)
        b = [0]*n
        product1 = 1
        for i in range(n):
            b[i] = product1
            product1 = product1*a[i]
        product2 = 1
        for i in range(n-1,-1,-1):
            b[i] = b[i]*product2
            product2 = product2*a[i]
        return b

 

 

 

 

 

标签:...,66,Offer,python,后缀,range,product2,product1,前缀
来源: https://blog.csdn.net/laurasam/article/details/120303185