Array prove safety offer- - Construction product array

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. (Note: The predetermined B [0] = A [1] * A [2] * ... * A [n-1], B [n-1] = A [0] * A [1] * ... * A [n-2];)

analysis

It was recorded with a variable multiplication product of the foregoing and the following.

Code

class Solution {
public:
    vector<int> multiply(const vector<int>& A) {
        int len = A.size();
        if (!len)
            return {};
        vector<int> B(len, 1);
        int start = 1;
        int end = 1;
        for (int i = 0; i < len; i++) {
            B[i] *= start;
            start *= A[i];
        }
        for (int i = len - 1; i >= 0; i--) {
            B[i] *= end;
            end *= A[i];
        }
        return B;
    }
};

 

Published 35 original articles · won praise 6 · views 6697

Guess you like

Origin blog.csdn.net/qq_35413770/article/details/105131223