数组产品除自我Javascript

时间:2016-06-11 22:04:36

标签: javascript algorithm

我一直在尝试使用Array Except Self的实现产品。我最初的想法是使用/tmp/ccFwG8do.o: In function `main': main.cpp:(.text+0x10): undefined reference to `NS::EXAMPLE::doSth()' collect2: error: ld returned 1 exit status indexes === array[j],但它不起作用。任何人都可以解释原因吗?

continue

5 个答案:

答案 0 :(得分:6)

您需要将ij进行比较,以了解何时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));

这是一个更紧凑的版本,使用mapreduce

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; }

答案 1 :(得分:5)

您可以使用以下解决方案(不使用除法运算符):

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;
}

答案 2 :(得分:2)

这是除self之外的数组乘积的O(n)解决方案。解决方案很冗长,但易于理解。

var test = [2, 3, 5, 6];

console.log(productExceptSelf(test));

function productExceptSelf(nums) {
    // We will need two arrays
    // One front and one from back
    var front = []; var back = [];
    
    // Set the first element of first to 1
    front[0] = 1; 
    
    // Set the last element of back to 1
    back[nums.length - 1] = 1;
    
    // Now multiply
    for(var i = 1; i < nums.length; i++) {
        front[i] = nums[i-1]*front[i-1];
    }
    
    for(var i = nums.length - 2; i >= 0; i--) {
        back[i] = nums[i+1]*back[i+1];
    }
    
    // Multiply front and back and put it in nums/ result
    for(var i = 0; i< front.length; i++) {
        nums[i] = front[i]*back[i];
    }
    

    // Return nums
    return nums;
};

这是如何工作的?让我们看一个例子:

arr   =  [1,  2,  3, 4]
front =  [1,  1,  2, 6]
back  =  [24, 12, 4, 1]
-----------------------
ans   =  [24, 12, 8, 6]   

答案 3 :(得分:0)

enter code here

function ProductArray(array) {
  let result = []
  if(array.length === 1) return [array[0]];
  for (let i = 0; i < array.length; i++) {
    let product = 1;
    for (let j = 0; j < array.length; j++) {
      product = (product * array[j]);
      actual = product/array[i];
    } 
    result.push(actual);
  }
  return result
}
    
console.log(ProductArray([1, 2, 3, 4]));//[24, 12, 8, 6]

答案 4 :(得分:-1)

这是我在JavaScript中的解决方案。我采取的方法是使用javascript数组方法forEach遍历给定的数组(值),在传递给forEach方法的箭头函数中,我使用了数组方法拼接来删除该索引处的当前元素,然后使用了数组方法reduce要获得数组中所有元素的乘积,即减去当前元素(因为已将其早些时候移除),然后将结果推入输出数组,然后使用unshift在该索引处添加已删除的元素,以便在下一次迭代中初始数组值将是完整的。

char8_t