Construct a product array

 Given an array A [0,1, ..., n-1], please construct an array B [0,1, ..., n-1], where the element B [i] = A [ 0] * A [1] * ... * A [i-1] * A [i + 1] * ... * A [n-1]. You cannot use division. (Note: Provision B [0] = A [1] * A [2] * ... * A [n-1], B [n-1] = A [0] * A [1] * ... * A [n-2];)

class Solution {
public:
    vector<int> multiply(const vector<int>& A) {
        int n=A.size();
        vector<int> B1(n,1);
        vector<int> B2(n,1);
        vector<int> B(n,1);
        for(int i=1;i<n;++i){
            B1[i]=B1[i-1]*A[i-1];
        }
        for(int i=n-2;i>=0;--i){
            B2[i]=B2[i+1]*A[i+1];
        }
        for(int i=0;i<n;i++){
            B[i]=B1[i]*B2[i];
        }
        return B;
    }
};

Use two arrays B1, B2 to save the sum of the products before and after position i, and then multiply these two arrays to generate a new array to get the product array

Guess you like

Origin www.cnblogs.com/qin5429/p/12693248.html