Leetcode 238. Product of Array Except Self 除本身之外的数组之积

127 阅读1分钟

[LeetCode] 238. Product of Array Except Self 除本身之外的数组之积

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of numsexcept nums[i].

Example:

Input: [1,2,3,4] Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

这道题给定我们一个数组,让我们返回一个新数组,对于每一个位置上的数是其他位置上数的乘积, 并且限定了时间复杂度 O(n),并且不让我们用除法。
这里需要使用O(1)空间复杂度
每个数都可以分为left和right相乘,比如

// Numbers:     2    3    4     5
// Lefts:            2  2*3 2*3*4
// Rights:  3*4*5  4*5    5

// Let’s fill the empty with 1:

// Numbers:     2    3    4     5
// Lefts:       1    2  2*3 2*3*4
// Rights:  3*4*5  4*5    5     1
export default (nums) => {
  const res = [];
  res[0] = 1;
  let sum = 1;
  const n = nums.length;
  // 计算left的值,这里可以得到每个i数字的Lefts的值
  for (let i = 1; i < n; i++) {
    res[i] = res[i - 1] * nums[i - 1];
  }
  // 为了保持空间复杂度为O(1),使用Rights保持右侧的数值
  let right = 1;
  for (let i = n - 1; i >= 0; i--) {
    res[i] *= right;
    right *= nums[i];
  }
  return res;
};