[Algorithm] Array production problem
Array Problem ALGORITHM production
2023-09-14 08:59:15 时间
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]
相关文章
- Array 数组的几种排序方法与常用添加数组元素方法
- CF1748E Yet Another Array Counting Problem
- 【说站】javascript中Array.slice()如何使用
- 【说站】js中Array.from的用法
- Remove Duplicates from Sorted Array详解程序员
- PHP array_reduce原理详解编程语言
- array用Redis轻松操控Byte Array(redisbyte)
- 收集的一些Array及String原型对象的扩展实现代码
- php数组函数序列之array_values()获取数组元素值的函数与方法
- Array.prototype.concat不是通用方法反驳[译]
- 解析C#中[],List,Array,ArrayList的区别及应用
- phpsybase_fetch_array使用方法
- java接口Array介绍
- php计算数组相同值出现次数的代码(array_count_values)