【Sword Finger】-66-Construct the product array

 

The difficulty of this question is that if you can't use division and use double loops, it will time out.

Idea: Use left[i] to store the product of all data on the left of a[i], right[i] represents the product of all data on the right of a[i], then res[i]=right[i]*left[i]

class Solution {
public:
    vector<int> constructArr(vector<int>& a) {
        int n=a.size();
        vector<int> res(n);
        if(n==0)return res;
        vector<int> left(n);
        vector<int> right(n);
        left[0]=right[n-1]=1;
        for(int i=1;i<n;i++)
            left[i]=left[i-1]*a[i-1];
        for(int i=n-2;i>=0;i--)
            right[i]=right[i+1]*a[i+1];
        for(int i=0;i<n;i++)
            res[i]=left[i]*right[i];
        
        
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/qq_39328436/article/details/114760417