题目:
给你一个整数数组 nums
,返回 数组 answer
,其中 answer[i]
等于 nums
中除 nums[i]
之外其余各元素的乘积 。
题目数据 保证 数组 nums
之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。
请 不要使用除法,且在 O(n)
时间复杂度内完成此题。
思路:除nums[i]
以外的乘积包含左侧乘积与右侧乘积,可以先计算出所有位置上的左右侧乘积,然后遍历数组取对应位置两数相乘得到最终结果
优化:
没有构造右侧乘积数组,而是用一个遍历来跟踪右边元素的乘积
Python:
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = len(nums)
answer = [0]*length
answer[0] = 1
for i in range(1, length):
answer[i] = nums[i - 1] * answer[i - 1]
R = 1;
for i in reversed(range(length)):
answer[i] = answer[i] * R
R *= nums[i]
return answer