给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除了 nums[i] 之外其余各元素的乘积 。
题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。
请 **不要使用除法,**且在 O(n) 时间复杂度内完成此题。
function productExceptSelf(nums: number[]): number[] {
const n =nums.length
const answer = new Array(n)
//第一次遍历,积累左侧的乘积
//第一个元素的左侧乘积初始话为 1
answer[0]=1
for(let i=1;i<n;i++){
answer[i] = answer [i -1] * nums [i-1]
}
//第二次从右到左进行遍历
//用一个累计值来存储从右到左的乘积
let anccumulator = 1 //最右侧的乘积为 1
for(let i = n-1; i>=0;i--){
//已有的前缀积*累计值
answer[i] = answer[i] * anccumulator
anccumulator *= nums[i]
}
return answer
};