我一直在尝试实现 Array Except Self 的产品。我最初的想法是使用 indexes === array[j]
和 continue
,但它不起作用。谁能解释一下为什么?
var array = [1,2,3,4];
function productOfArrayExceptSelf(array){
var result = 0;
var resultArray = [];
var indexes;
for(var i = 0; i < array.length; i++){
for(var j = 0; j < array.length; j++){
indexes = array[j];
if(indexes === array[j]){
continue;
}
}
}
return result;
}
最佳答案
您需要将 i
与 j
进行比较,以了解何时继续
。此外,你没有任何乘法发生。
这是一个工作片段:
function productOfArrayExceptSelf(array){
var resultArray = [], product;
for(var i = 0; i < array.length; i++){
product = 1;
for(var j = 0; j < array.length; j++){
if(i !== j) product *= array[j];
}
resultArray.push(product);
}
return resultArray;
}
// Sample data
var array = [1,2,3,4];
console.log(productOfArrayExceptSelf(array));
这是一个更紧凑的版本,使用了 map
和 reduce
:
function productOfArrayExceptSelf(array){
return array.map(function (_, i) {
return array.reduce(function (product, val, j) {
return product * (i === j ? 1 : val);
}, 1);
});
}
var array = [1,2,3,4];
console.log(productOfArrayExceptSelf(array));
...这是一个在 O(n) 而不是 O(n²) 中运行的 ES6 版本。这个想法是将所有数字的乘积除以相关索引处的数字。当然,当数组中有零时,需要一些注意事项:
function productOfArrayExceptSelf(array){
const [product, zeroAt] = array.reduce(([product, zeroAt], val, j) =>
val ? [product * val, zeroAt]
: zeroAt >= 0 ? [0, -1] // there is more than one zero
: [product, j] // there is a zero at index j
, [1, -2]);
return zeroAt == -1 ? array.fill(0) // there is more than one zero
: zeroAt >= 0 ? Object.assign(array.fill(0), { [zeroAt]: product })
: array.map((val, i) => product / val);
}
console.log(productOfArrayExceptSelf([1,2,3,4]));
console.log(productOfArrayExceptSelf([1,0,3,4]));
console.log(productOfArrayExceptSelf([1,0,0,4]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 数组的产品,除了自己的 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37768893/