

LeetCode Hot 100:除自身以外数组的乘积
本期讲 LeetCode Hot 100 的「除自身以外数组的乘积」。题目给一个整数数组
nums,要求返回 answer,其中 answer[i] 等于除了 nums[i] 以外其余所有元素的乘积;题目明确要求不要使用除法,并在 O(n) 时间内完成。示例包括 [1,2,3,4] -> [24,12,8,6] 和 [-1,1,0,-3,3] -> [0,0,9,0,0]。详见 力扣 238. 除了自身以外数组的乘积。这题考察的不是乘法本身,而是把「除掉自己」改写成两个独立状态:当前位置左侧所有数的乘积,乘上当前位置右侧所有数的乘积。第一遍从左到右,把左侧乘积写进
answer;第二遍从右到左,用一个 suffix 变量把右侧乘积补乘回去。输出数组不算额外空间,所以这个写法满足进阶要求里的 O(1) 额外空间。function productExceptSelf(nums) {
const n = nums.length;
const answer = new Array(n).fill(1);
let prefix = 1;
for (let i = 0; i < n; i++) {
answer[i] = prefix;
prefix *= nums[i];
}
let suffix = 1;
for (let i = n - 1; i >= 0; i--) {
answer[i] *= suffix;
suffix *= nums[i];
}
return answer;
}时间复杂度是
O(n),因为数组只被左右各扫一遍;额外空间复杂度是 O(1),不计返回的 answer。包含 0 的输入不需要额外分支:前缀积和后缀积会自然把不该保留的位置乘成 0。This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.
