[Sword refers to offer] Do not use division, build a product array, C++ implementation

# topic

image

# ideas

Let C[i] = A[0] * A[1] * … * A[i-1], D[i]A[i +1] * … * A[n-1], then C[i ] is calculated from top to bottom, that is, C[i] = C[i-1] * A[i-1]. D[i] is calculated from bottom to top, i.e. D[i] = D[i+1] * A[i+1] . By C[i] and D[i], the formula for calculating B[i] can be exited, ie B[i] = C[i] * D[i] = C[i-1] * A[i-1] * D[i+1] * A[i+1] .

image

# code

#include <iostream>
#include <vector>
using namespace std;

// Build the product array
 class Solution {
public:
    vector<int> multiply(const vector<int>& A) 
    {
        // store the result
        int n=A.size();
        vector<int> b(n);
        
        // calculation result
        int ret;
        ret = 1;// 存储C[i]
        for(int i=0;i<n;ret*=A[i++]){
            b [i] = ret;
        }
        
        ret = 1;// 存储D[i]
        for(int i=n-1;i>=0;ret*=A[i--]){
            b [i] * = ret;
        }
        return b;
    }
};

intmain()
{
    const vector<int> a = {1,2,3,4,5};
    Solution solution;
    solution.multiply(a);
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326271299&siteId=291194637