构建乘积数组 (主思路B[i]=lf[i]*rt[n-1-i])——Yuanjrah
构建乘积数组
http://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46
/*
*Author@Yuanjrah
*利用两个数组保存i位置左右两侧所有元素乘积,然后B[i]等于i位置左侧乘积 * 右侧乘积,
*初始化0位置左侧乘积为1,n-1位置右侧乘积为1
*1.定义数组lf和rt
- lf[i]用来存放A数组左侧A[0] * A[1] * ...*A[i-1],初始化lf[0]=1
- rt[i]存放A数组右侧A[n-1] * A[n-2] * ...*A[i+1],初始化rt[0]=1
- 2.B[i] = lf[i] * rt[n-1-i]
- B[0] = lf[0] * rt[n-1] = 1 * 1 * A[n-1] * A[n-2] *... * A[1]
- B[1] = lf[1] * rt[n-2] = 1 * A[0] * 1 * A[n-1] * A[n-2] *... *A[2]
- B[n-1] = lf[n-1] * rt[0] = 1 * A[0] * A[1] *... * A[n-2] * 1
- /
class Solution { public: vector<int> multiply(const vector<int>& A) { vector<int>ans;//结果 vector<int>lf, rt;//左侧乘积,右侧乘积 int len=A.size(); int digit_lf=1,digit_rt=1; for(int i=0;i<len;i++){ //便于计算B[0],B[n-1] //B[0]=lf[0]*rt[n-1] lf.push_back(digit_lf);//lf[0]=1 rt.push_back(digit_rt);//rt[0]=1 digit_lf*=A[i]; digit_rt*=A[len-1-i];//A数组倒数第i+1位 } for(int i=0;i<len;i++){ ans.push_back(lf[i]*rt[len-1-i]); } return ans; } };