【剑指offer-解题系列(52)】构建乘积数组

来源:互联网 发布:linux jdk1.7下载 编辑:程序博客网 时间:2024/05/21 22:24

题目描述

给定一个数组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]。不能使用除法。

分析

采用两个数组 A[n] , B[n]分别记录除去第 i 个数后,

A数组记录从 1 ~ i-1 个数的乘积,

B数组记录从 i+1 ~ n 个数的乘积。

最后,只需要再次遍历数组,把AB数组相乘就可以得到最后结果
 

代码实现

    vector<int> multiply(const vector<int>& A) {
    int n = A.size();
        vector<int>res;
        
        if(n<=0)
            return res;
        int *a =new int[n];
        int *b =new int[n]; 
        memset(a,0,n*sizeof(int)); a[0]  =1;
        memset(b,0,n*sizeof(int)); b[n-1]=1;
        ///////////////////////////
        
        for(int i=1;i<n;i++){
            a[i]=a[i-1]*A[i-1];
        }
        for(int i=n-2;i>=0;i--){
            b[i]=b[i+1]*A[i+1];
        } 
        for(int i=0;i<n;i++){
            res.push_back(a[i] *b[i]);
        }
        //////////////////////////
        delete a;
        delete b;
        return res;
    }


 

原创粉丝点击