我在一次工作面试中被问到这个问题,我想知道其他人是如何解决这个问题的。我最擅长使用Java,但也欢迎使用其他语言的解决方案。
给定一个数字数组nums,返回一个数字数组products,其中products[i]是所有nums[j]的乘积,j != i。
输入:[1,2,3,4,5]
输出:[(2 * 3 * 4 * 5),(1 * 3 * 4 * 5),(1 * 2 * 4 * 5),(1 * 2 * 3 * 5),(1 * 2 * 3 * 4)]
= [120, 60, 40, 30, 24]
你必须在O(N)中不使用除法来做这个。
下面是另一个简单的概念,可以解决O(N)中的问题。
int[] arr = new int[] {1, 2, 3, 4, 5};
int[] outArray = new int[arr.length];
for(int i=0;i<arr.length;i++){
int res=Arrays.stream(arr).reduce(1, (a, b) -> a * b);
outArray[i] = res/arr[i];
}
System.out.println(Arrays.toString(outArray));
php版本
使用不除法的array_product函数。
如果我们将i的值临时设为1,那么数组product将完全满足我们的需要
<?php
function product($key, $arr)
{
$arr[$key] = 1;
return array_product($arr);
};
$arr = [1, 2, 3, 4, 5];
$newarr = array();
foreach ($arr as $key => $value) {
$newarr[$key] = product($key, $arr);
}
print_r($newarr);
我用Javascript想出了两个解决方案,一个有除法,一个没有
//不除法
函数methodOne(arr) {
加勒比海盗。Map (item => {
加勒比海盗。Reduce ((result, num) => {
If (num !== item) {
结果=结果* num;
}
返回结果;
}, 1)
});
}
//使用除法
函数methodTwo(arr) {
Var mul = arr。Reduce ((result, num) => {
结果=结果* num;
返回结果;
}, 1)
加勒比海盗。Map (item => mul/item);
}
console.log(methodOne([1,2,3,4,5]));
console.log(methodTwo([1,2,3,4,5]));