- 常数级别的空间复杂度、O(n)时间复杂度、不用除法
- 除法-》一开始就乘1
- 遍历两遍,1、计算当前数左边的乘积 2、计算当前数右边的乘积 3、累乘
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
#
nlen = len(nums)
res = [1] * nlen
tmp = 1
# 遍历两遍
# 1、计算当前数左边的乘积m1
for i in range(1, nlen): # 顺序累乘
res[i] = res[i-1] * nums[i-1]
# 注意i=0时,相当于左边没有数了,不用乘,在乘法中也就相当于乘1
print(res)
# 2、计算当前数右边的乘积m2,3、累乘到m1上
# 题目提示中表明,nums.length>=2
for j in range(nlen-2, -1, -1):# 倒序累乘
tmp *= nums[j+1] # 2.1 右边乘积
res[j] *= tmp # 2.2 累乘到m1上
print(res)
return res
参考这个链接下的评论和代码:除自身以外数组的乘积(上三角,下三角)