不用除法求一个数组中除自己外的元素乘积

啥也不说,上代码

#include <vector>
class RangeMultiply {
public:
    /* abcdefg a g ab fg abc efg abcd defg abcde cdefg abcdef bcdefg */
    vector<int> calculate(const vector<int>& data) {
        vector<int> l(data.size() - 1);
        vector<int> r(data.size() - 1);
        int lMul = 1;
        int rMul = 1;
        for (int i = 0; i < data.size() - 1; ++i) {
            lMul *= data[i];
            rMul *= data[data.size() - 1 - i];
            l[i] = lMul;
            r[i] = rMul;
        }
        vector<int> ans;
        ans.resize(data.size());
        ans[0] = r[r.size() - 1];
        ans[data.size() - 1] = l[l.size() - 1];
        for (int i = 1; i < data.size() - 1; ++i) {
            ans[i] = l[i - 1] * r[r.size() - 1 - i];
        }
        return ans;
    }
};
点赞