我知道这个问题之前已经多次浮现在StackOverflow之上,但我试图围绕为什么特别是一个解决方案实际工作。完整的问题是:
给定一个整数数组,返回一个输出数组,使得output [i]等于数组中除自身之外的所有元素的乘积。 (在没有除法的情况下在O(n)中解决这个问题)
我在JavaScript中遇到的解决方案是:
function productExceptSelf(numArray) { // sample input: [2, 2, 4, 1]
var product = 1;
var size = numArray.length;
var result = [];
for (var x = 0; x < size; x++) {
result.push(product);
product = product * numArray[x];
}
// result arr: [1, 2, 4, 16]
product = 1;
for (var i = size - 1; i > -1; i--) {
result[i] = result[i] * product;
product = product * numArray[i];
}
// result arr: [8, 8, 4, 16]
return result;
}
据我所知,在第一个循环中,数组中的前3个元素乘以乘积(第一次推送1,result
数组中总共4个整数)。
我不太清楚我是否理解在第二个循环中如何循环并执行基本相同的操作会给我们提供我们正在寻找的答案。这种方法有名称吗?我知道这是一个很奇怪的问题,但请耐心等待。
答案 0 :(得分:1)
第一个循环将每个nums - 1/1, 1/2, 2/4, 2/3
diff - 0 , -1 , -2 , -1
max is 3/4 using 1/1 and 2/3
与每个output[i]
相乘,其中j <1。一世。第二个将每个numArray[j]
与每个output[i]
相乘,其中j>一世。最终结果是每个numArray[j]
乘以output[i]
,其中j≠i。
答案 1 :(得分:1)
可能在每次通过循环时说明数组的内容将有助于理解
// forwards loop through
x = 0:
product 1
result [1]
numArray[{2}, 2, 4, 1]
product after 2
x = 1
product 2
result [1, 2]
numArray[2, {2}, 4, 1]
product after 4
x = 2
product 4
result [1, 2, 4]
numArray[2, 2, {4}, 1]
product after 16
x = 3
product 16
result [1, 2, 4, 16]
numArray[2, 2, 4, {1}]
product after 16
Now the other direction
Product reset to 1
// backwards loop
i = 3
product 1
result before = [1, 2, 4, {16}]
result after = [1, 2, 4, {16}] -- (16 * 1) = 16
numArray[2, 2, 4, {1}]
product after 1 -- (1*1) = 1
i = 2
product 1
result before [1, 2, {4}, 16]
result after = [1, 2, {4}, 16] -- (4 * 1) = 4
numArray[2, 2, {4}, 1]
product after 4 -- (4*1) = 4
i = 1
product 4
result before [1, {2}, 4, 16]
result after = [1, {8}, 4, 16] -- (2 * 4) = 8
numArray[2, {2}, 4, 1]
product after 8 -- (4*2) = 8
i = 0
product 8
result before [{1}, 2, 4, 16]
result after = [{8}, 8, 4, 16] -- (1 * 8) = 8
numArray[{2}, 2, 4, 1]
product after 16 -- (8*2) = 16 (unused)