题目
给你一个长度为 n 的整数数组 nums
,其中 n > 1,返回输出数组 output
,其中 output[i]
等于 nums
中除 nums[i]
之外其余各元素的乘积。
示例:
输入: [1,2,3,4]
输出: [24,12,8,6]
提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。
说明: 请不要使用除法,**且在 时间复杂度内完成此题。
方案一
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
if not nums or len(nums) == 1:
return nums
left = [1] * len(nums)
for i in range(len(nums) - 1):
left[i + 1] = left[i] * nums[i]
right = [1] * len(nums)
for i in range(len(nums) - 2, -1, -1):
right[i] = right[i + 1] * nums[i + 1]
return [left[i] * right[i] for i in range(len(nums))]
- 我们不必将所有数字的乘积除以给定索引处的数字得到相应的答案,而是可以利用索引处左侧的所有数字乘积和右侧所有数字的乘积相乘得到答案。
算法:
- 初始化两个空数组
L
和R
。对于给定索引i
,L[i]
代表的是i
左侧所有数字的乘积,R[i]
代表的是i
右侧所有数字的乘积。 - 填充
L
和R
数组的值。 - 当
R
和L
数组填充完成,我们只需要在输入数组上迭代,且索引i
处的值为:L[i]*R[i]
。
空间复杂度为的算法请参考第二个参考链接。
参考链接
https://leetcode-cn.com/explore/interview/card/2020-top-interview-questions/280/array/1254/
https://leetcode-cn.com/problems/product-of-array-except-self/solution/chu-zi-shen-yi-wai-shu-zu-de-cheng-ji-by-leetcode/