题目描述

给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]A[1]...A[i-1]A[i+1]...A[n-1]。不能使用除法。

分析

设结果数组为res,给定数组为arr=[a,b,c,d],首先取:

  • res[0] = 1
  • res[1] = res[0]*arr[0] = a
  • res[2] = res[1]*arr[1] = ab
  • res[3] = res[2]*arr[2] = abc

再取temp = arr[4] = d

  • res[2] = res[2]temp = abd,temp = temparr[2] = cd
  • res[1] = res[1]temp = acd,temp = temparr[1] = bcd
  • res[0] = res[0]temp = bcd,temp = temparr[0] = abcd

至此,res数组正确构造完毕。

代码实现

function multiply(arr)
{
    var res = [], index = 1;
    res[0] = 1;
    
    for(var i = 0;i < arr.length-1;i++) {
        res[index] = res[index-1] * arr[i];
        index++;
    }
    
    var temp = arr[arr.length-1], index = res.length-2;
    for(var i = arr.length-2;i >= 0;i--) {
        res[i] *= temp;
        temp *= arr[index--];
    }
    
    return res;
}

耳东
766 声望51 粉丝

知乎专栏:[链接]