【刷算法】构建乘积数组

问题形貌

给定一个数组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;
}
    原文作者:亚古
    原文地址: https://segmentfault.com/a/1190000015807516
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞