码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithm] Array production problem

时间:2019-03-05 09:40:43      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:amp   UNC   i++   code   ble   integer   dex   new   divide   

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

 

For example [1,2,3,4,5]:

技术图片

We can divide into Right and Left array two parts. For Left[0] and Right[n-1], we set to 1;
 
技术图片
We can get the product results like the image above.
Now the only thing we need to do is Left * Right. 
 
The way Left calculated is:
Left[i] = Left{i-1] * arr[i-1], i start from 1, i++
 
The way Right calculated is:
Right[j] = Right[j+1] * arr[j+1], j start from n-2, j--
 
function productArr(arr) {
  let left = [];
  let right = [];
  let prod = [];
  left[0] = 1;
  right[arr.length - 1] = 1;

  for (let i = 1; i <= arr.length -1; i++) {
    left[i] = left[i-1] * arr[i-1];
  }

  for (let j = arr.length - 2; j >=0; j--) {
    right[j] = right[j+1] * arr[j+1];
  }

  prod = left.map((l, i) => l * right[i]);

  return prod
}

console.log(productArr([1, 2, 3, 4, 5])); // [120, 60, 40, 30, 24]

 

[Algorithm] Array production problem

标签:amp   UNC   i++   code   ble   integer   dex   new   divide   

原文地址:https://www.cnblogs.com/Answer1215/p/10474421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!