我在一次工作面试中被问到这个问题,我想知道其他人是如何解决这个问题的。我最擅长使用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)中不使用除法来做这个。
根据Billz的回答——抱歉我不能评论,但这里是一个正确处理列表中重复项的scala版本,可能是O(n):
val list1 = List(1, 7, 3, 3, 4, 4)
val view = list1.view.zipWithIndex map { x => list1.view.patch(x._2, Nil, 1).reduceLeft(_*_)}
view.force
返回:
List(1008, 144, 336, 336, 252, 252)
我用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]));