238. 除了自身以外数组的乘积
- 题号:238
- 来源:LeetCode
- 难度:中等
- 标签:
前缀和数组 - 语言:Python
- 解法:1 个
- 作者:lmliheng
- 最近更新:2026-09-29
Python · O(n) 时间 · O(n) 空间 · 更新于 2026-09-29
先左积后右积,两遍扫描不用除法
python
"""
@difficulty medium
@tags 前缀和,数组
@time O(n)
@space O(n)
@note 先左积后右积,两遍扫描不用除法
238. 除了自身以外数组的乘积
"""
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n=len(nums)
res=[1]*n
for i in range(1,n):
res[i]=nums[i-1]*res[i-1]
temp=1
# 1 1 2 6
# temp 24 12 4 1
for i in range(n-1,0,-1):
temp*=nums[i]
print(i,temp)
res[i-1]*=temp
return res源码:python/leetcode/hot100/16.py
在 GitHub 上查看题目所在目录:lmliheng/algorithm