class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
p = [1] * n; s = 1
for i in range(1, n):
p[i] = p[i-1] * nums[i-1]
for i in range(n - 1, -1, -1):
p[i] *= s
s *= nums[i]
return p
# 前后缀数组
# p前缀数组,s后缀数组
# 因为空间复杂度要求 O(1),因此结果返回也使用p数组,同时后缀数组存储在变量中
# 时间复杂度:O(N)
# 空间复杂度:O(1)
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
p = [1] * n; s = [1] * n
res = list()
for i in range(1, n):
p[i] = p[i-1] * nums[i-1]
for i in reversed(range(n - 1)):
s[i] = s[i+1] * nums[i+1]
for i in range(n):
res.append(p[i] * s[i])
return res