[leetCode]剑指 Offer 66. 构建乘积数组
解法
把A数组分为两部分:
A[0,...,i-1]
A[i+1,...,n-1]
数组B可以用一个矩阵创建:
另C[i]
为矩阵第i
行左半部分的乘积,D[i]
为矩阵第i
行右半部分的乘积。C[i]
可以自上而下计算:C[i] = C[i-1] * A[i-1]
,D[i]
可以自下而上计算:D[i] = D[i+1]*A[i+1]
,所以B[i] = C[i] * D[i]
class Solution {
public int[] constructArr(int[] a) {
if (a == null || a.length == 0) return new int[]{};
int[] b = new int[a.length];
b[0] = 1;
for (int i = 1; i < a.length; i++) {
b[i] = b[i-1] * a[i-1];
}
int temp = 1;
for (int i = a.length - 2; i >= 0; i--) {
temp *= a[i+1];
b[i] *= temp;
}
return b;
}
}