/** * https://leetcode.cn/problems/product-of-array-except-self/?envType=study-plan-v2&envId=top-interview-150 * @param {number[]} nums * @return {number[]} */ const productExceptSelf = function (nums) { const n = nums.length; const result = new Array(n).fill(1); // 计算每个位置左侧的乘积 let leftProduct = 1; for (let i = 0; i < n; i++) { result[i] = leftProduct; leftProduct *= nums[i]; } // 计算每个位置右侧的乘积并与左侧乘积相乘 let rightProduct = 1; for (let i = n - 1; i >= 0; i--) { result[i] *= rightProduct; rightProduct *= nums[i]; } return result; };