1. 程式人生 > >[劍指offer] 51. 構建乘積陣列

[劍指offer] 51. 構建乘積陣列

題目描述

給定一個數組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]。不能使用除法。

思路:

當作一個上三角和下三角,分別用兩個for去乘上三角和下三角。

class Solution
{
  public:
    vector<int> multiply(const vector<int> &A)
    {
        vector<int> B;
        if (A.empty())
            
return B; int len = A.size(); B.push_back(1); for (int i = 1; i < len; i++) { B.push_back(B[i - 1] * A[i - 1]); } int temp = 1; for (int i = len - 2; i >= 0; i--) { temp *= A[i + 1]; B[i] *= temp; }
return B; } };