1. 程式人生 > >51、劍指offer--構建乘積數組

51、劍指offer--構建乘積數組

left tor return 劍指offer tex -s ace line vector

題目描述 給定一個數組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--構建乘積數組