Voyz's Studio.

LeetCode算法笔记--除自身以外数组的乘积

字数统计: 161阅读时长: 1 min
2021/02/21 Share

LeetCode算法笔记-Day69

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 nums except nums[i].

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

1
2
3
4
Example:

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

左右乘积列表

  • 索引 i 处的值为:L[i] * R[i]

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
const len = nums.length;
let l_arr = new Array(len).fill(1),
r_arr = new Array(len).fill(1);

for(let i=1;i<len;i++){
l_arr[i] = l_arr[i-1] * nums[i-1];
r_arr[len-1-i] = r_arr[len-i] * nums[len-i];
}

for(let k=0;k<len;k++){
nums[k] = l_arr[k] * r_arr[k]
}

return nums;
};
CATALOG
  1. 1. LeetCode算法笔记-Day69
    1. 1.1. 238. Product of Array Except Self
    2. 1.2. 左右乘积列表
      1. 1.2.1. Answer: