Leetcode|前缀和(双向前缀积)|剑指 Offer 66. 构建乘积数组

2021-09-22 11:22:58 浏览数 (1)

1 前缀和(双向前缀积)

代码语言:javascript复制
class Solution {
public:
    vector<int> constructArr(vector<int>& a) {
        int size = a.size();
        vector<int> pre(size   1, 1);
        vector<int> last(size   1, 1);
        vector<int> res(size, 1);
        // 前缀积(从左至右乘积)
        for (int i = 0; i < size; i  )
            pre[i   1] = pre[i] * a[i];
        // 后缀积
        for (int i = size - 1; i >= 0; i--)
            last[i] = last[i   1] * a[i];
        // 计算结果
        for (int i = 0; i < size; i  ) 
            res[i] = pre[i] * last[i   1];
        return res;
    }
};

0 人点赞