Skip to main content

238. Product of Array Except Self

分析


题解

function productExceptSelf(nums: number[]): number[] {
const prefix = [], suffix = []
prefix[0] = 1
suffix[nums.length - 1] = 1
for (let i = 1; i < nums.length; i++) {
prefix[i] = prefix[i - 1] * nums[i - 1]
}
for (let i = nums.length - 2; i >= 0; i--) {
suffix[i] = suffix[i + 1] * nums[i + 1]
}

const ans = []

for (let i = 0; i < nums.length; i++) {
ans[i] = prefix[i] * suffix[i]
}

return ans
};