目录
思路:
代码:
思路:
直接计算前缀乘积,后缀乘积,然后相乘即可
开始我还在想,遍历一次i,怎么能同时计算前缀乘积和后缀乘积,事实上分开计算比较方便。。
代码:
class Solution:def productExceptSelf(self, nums: List[int]) -> List[int]:n = len(nums)left = [1] * nright = [1] * nanswer = [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