首页 > 代码库 > 51、剑指offer--构建乘积数组

51、剑指offer--构建乘积数组

题目描述
给定一个数组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]。不能使用除法。
 
解题思路:B[I] = (A[0]*A[1]*...*A[I-1]) * (A[I+1]*A[I+2]*...*A[n-1])
C[i] = A[0]*A[1]*...*A[I-1] = C[i-1]*A[i-1];
D[i] = A[I+1]*A[I+2]*...*A[n-1] = A[i+1]*D[i+2];
B[i] = C[i]*D[i];
 1 class Solution {
 2 public:
 3     //B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]
 4     //从左到右算 B[i]=A[0]*A[1]*...*A[i-1]
 5     //从右到左算B[i]*=A[i+1]*...*A[n-1]
 6     //C[i] = C[i-1] * A[i-1]
 7     //D[i] = D[i+1] * A[i+1];
 8     vector<int> multiply(const vector<int>& A) {
 9         int length = A.size();
10         vector<int> B(length);
11         B[0] = 1;
12         for(int i=1;i<length;i++)
13         {
14             B[i] = B[i-1] * A[i-1];
15         }
16         double temp = 1;
17         for(int i=length-2;i>=0;--i)
18         {
19             temp = temp * A[i+1];
20             B[i] *= temp;
21         }
22         return B;
23     }
24 };

 

51、剑指offer--构建乘积数组