剑指OFFER----面试题66. 构建乘积数组

链接:https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/

代码

class Solution {
public:
    vector<int> constructArr(vector<int>& a) {
        if (a.empty()) return vector<int>();

        int n = a.size();
        vector<int> res(n);

        for (int i = 0, p = 1; i < n; ++i) {
            res[i] = p;
            p *= a[i];
        }

        for (int i = n - 1, p = 1; i >= 0; --i) {
            res[i] *= p;
            p *= a[i];
        }
        return res;
    }
};
posted @ 2020-03-16 14:31  景云ⁿ  阅读(90)  评论(0编辑  收藏  举报