66. 构建乘积数组

https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13&tqId=11204&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&from=cyc_github&tab=answerKey

class Solution {
public:
    vector<int> multiply(const vector<int>& A) {
        vector<int> left;
        vector<int> right;
        int size = A.size();
        left.resize(size);
        right.resize(size);
        for(int k=0;k<size;++k){
            int r = size-1-k;
            if(k==0){
                left[0] = A[0];
                right[r] = A[r];
            }else{
                left[k]=left[k-1]* A[k];
                right[r] = right[r+1]*A[r];
            }
        }
        vector<int> ans;
        for(int i=0;i<size;++i){
            if(i == 0){
                ans.push_back(right[1]);
            }else if(i == size-1){
                ans.push_back(left[i-1]);
            }else{
                ans.push_back(left[i-1]*right[i+1]);
            }
        }
        return ans;
    
    }
};
posted @ 2021-03-27 19:37  rxh1999  阅读(41)  评论(0编辑  收藏  举报