面试题66

给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B 中的元素 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。

示例:

输入: [1,2,3,4,5]
输出: [120,60,40,30,24]

提示:

  • 所有元素乘积之和不会溢出 32 位整数

  • a.length <= 100000

Solutions

  • The same as problem 238

  1. prefix/suffix producy O(n) S(1)

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

        int suffix = 1;
        for (int i = a.size() - 1; i >= 0; i--) {
            res[i] *= suffix;
            suffix *= a[i];
        }

        return res;
    }
};

Or update prefix/suffix product in one loop.

class Solution {
public:
    vector<int> constructArr(vector<int>& a) {
        if (a.size() <= 1) return a;
        vector<int> res(a.size(), 1);

        int prefixp = 1, suffixp = 1;
        for (int i = 0, j = a.size() - 1; j >= 0; i++, j--) {
            res[i] *= prefixp;
            res[j] *= suffixp;
            prefixp *= a[i];
            suffixp *= a[j];
        }

        return res;
    }
};

Last updated

Was this helpful?