本文最后更新于:2022年4月9日 中午
给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
示例:
| 输入: [1,2,3,4] 输出: [24,12,8,6]
|
提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
Solution
- 建立左右乘积列表
- 对于给定索引 i ,使用它左边所有数字的乘积乘以右边所有数字的乘积。
- 时间复杂度:O(N),其中 N 指的是数组
nums 的大小。
- 空间复杂度:O(N),其中 N 指的是数组
nums 的大小。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: length = len(nums) L, R, answer = [0]*length, [0]*length, [0]*length L[0] = 1 for i in range(1, length): L[i] = nums[i - 1] * L[i - 1] R[length - 1] = 1 for i in reversed(range(length - 1)): R[i] = nums[i + 1] * R[i + 1]
for i in range(length): answer[i] = L[i] * R[i] return answer
|
官方题解思路:
- 先把
answer 作为 L 数组。
- 用一个遍历来跟踪右边元素的乘积。并更新数组
answer[i]=answer[i]*R。然后 R 更新为 R=R*nums[i],其中变量 R 表示的就是索引右侧数字的乘积。
| class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: ans = [0]*len(nums) ans[0] = 1 for i in range(1, len(nums)): ans[i] *= nums[i-1] R = 1 for i in range(len(nums)-1, -1, -1): ans[i] = ans[i] * R R *= nums[i] return ans
|