[Prove safety offer] - Array Construction product

Title Description

Given an array A [0,1, ..., n-1], please construct an array B [0,1, ..., n-1], where B is the element B [i] = A [ 0] * A [1] * ... * A [i-1] * A [i + 1] * ... * A [n-1]. You can not use the division.

Ideas:

Seeking B [i] when two steps, first find the left multiplying all the A, and then seek the right multiplying all A, i.e. multiplying the two will eventually give the corresponding B. In particular by two cycles, multiplies them to obtain different B [i], the following code:

class Solution {
public:
    vector<int> multiply(const vector<int>& A) {
        int len = A.size();
        vector<int> B(len);
        if(len == 0)
            return B;
//总结:第0位和第n-1位为特殊情况,其对应左侧和右侧乘积均当做1,for循环都从第二位和倒数第二位起
        B[0] = 1;//此处的B[0]代表第0位前A[i]的乘积,初始化为1
        for(int i=1;i<len;i++){  //累乘求第1位到第n-1位前面所有A[i]的乘积
            B[i] = B[i-1]*A[i-1];
        }
        int temp = 1; //此处的temp代表最后1位后面A[i]的乘积,对应的是最后一位,所以初始化为1
        for(int i=len-2;i>=0;i--){//累乘求第n-2位到第0位前面所有A[i]的乘积
            temp *=A[i+1];
            B[i] *= temp;
        }
        return B;
    }
};

Guess you like

Origin blog.csdn.net/yuemingyang7010/article/details/92365123