目录
思路:
代码:
思路:
直接计算前缀乘积,后缀乘积,然后相乘即可
开始我还在想,遍历一次i,怎么能同时计算前缀乘积和后缀乘积,事实上分开计算比较方便。。
代码:
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
left = [1] * n
right = [1] * n
answer = [1] * n
# 计算左边的乘积数组
for i in range(1, n):
left[i] = left[i-1] * nums[i-1]
# 计算右边的乘积数组
for i in range(n-2, -1, -1):
right[i] = right[i+1] * nums[i+1]
# 计算最终的结果
for i in range(n):
answer[i] = left[i] * right[i]
return answer