[Algorithm] Array production problem

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]

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10474421.html