spa*_*Dog 1 javascript algorithm
我一直在尝试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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下解决方案(不使用除法运算符):
function Product(arr){
var temp = [];
var product = 1;
for(var i=0; i<arr.length; i++){
temp[i] = product;
product *= arr[i];
}
product = 1;
for(var i=arr.length-1; i>=0; i--){
temp[i] *= product;
product *= arr[i];
}
return temp;
}
Run Code Online (Sandbox Code Playgroud)
你需要比较i,j知道什么时候continue.而且,你无处可逃.
这是一个工作片段:
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));Run Code Online (Sandbox Code Playgroud)
这是一个更紧凑的版本,利用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));Run Code Online (Sandbox Code Playgroud)
......这是一个以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]));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1451 次 |
| 最近记录: |