ACWING86. Construction product array (the offer to prove safety)

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.

Sample
input: [1, 2, 3, 4, 5]

Output: [120, 60, 40, 30, 24]
Questions:

You can only use a constant space? (Outside array output in addition

Ideas:
maintenance of prefixes and suffixes to

class Solution {
public:
    vector<int> multiply(const vector<int>& A) {
        int n = A.size();
        vector<int>ans(n,1);
        if(!n) return ans;
        
        int p = 1;
        for(int i = 1;i < n;i++) {
            p *= A[i - 1];
            ans[i] *= p;
        }
        p = 1;
        for(int i = n - 2;i >= 0;i--) {
            p *= A[i + 1];
            ans[i] *= p;
        }
        return ans;
    }
};
Published 844 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/104976596