leetcode链接:https://leetcode-cn.com/problems/product-of-array-except-self/
问题描述:
给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
算法思路:
用L列表记录每个元素左边的乘积 L[i] = L[i-1] * nums[i-1],其中L[0]初始化成1。
用R列表记录每个元素右边的乘积R[i] = R[i+1] * nums[i+1], 其中R[-1]初始化成1。
最后的结果reult = L[i] * R[i]
空间复杂度o(n) 时间复杂度o(n)
代码如下:
# 方法1 时间o(n) 空间o(n)
def productExceptSelf(self, nums):
L = [0]*len(nums)
L[0] = 1
R = [0]*len(nums)
R[-1] = 1
result = [0]*len(nums)
for i in range(1,len(nums)):
L[i] = L[i-1]*nums[i-1]
for j in range(len(nums)-2,-1,-1):
R[j] = R[j+1] * nums[j+1]
for i in range(len(nums)):
result[i] = L[i] * R[i]
return result
# 方法2 时间o(n) 空间o(1)
def productExceptSelf(self, nums: List[int]) -> List[int]:
# 空间复杂度为o(n) 时间复杂度为o(n)
L = [0]*len(nums)
L[0] = 1
R = 1
for i in range(1,len(nums)):
L[i] = L[i-1]*nums[i-1]
for j in range(len(nums)-2,-1,-1):
R = R*nums[j+1]
L[j] *= R
return L