用JavaScript构造产品数组

我们需要编写一个包含数字数组的JavaScript函数。该函数应基于原始数组构造一个新数组。新数组的每个对应元素应是原始数组包括该元素的所有元素的乘积。

例如-

如果输入数组是-

const arr = [1, 2, 3, 4, 5];

那么输出数组应该是-

const output = [120, 60, 40, 30, 24];

我们必须在线性时间和恒定空间(显然不包括在构造新数组时所用的空间)中实现这一点。

示例

以下是代码-

const arr = [1, 2, 3, 4, 5];
const exclusiveProduct = (arr = []) => {
   // O(n) 时间复杂度
   const product = arr.reduce((acc, val) => acc * val);
   const res = [];
   // O(n) 时间复杂度
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      res[i] = product / el;
   };
   return res;
};
console.log(exclusiveProduct(arr));

输出结果

以下是控制台上的输出-

[120, 60, 40, 30, 24]