题
思
B[3]就是A[3]左边的数的乘积再乘上A[3]右边的数的乘积,而左侧的乘积和右侧的乘积又可以用dp一次遍历来算。
代码
class Solution {
public int[] constructArr(int[] a) {
if(a.length == 0) {
return new int[]{};
}
int[] dpLeft = new int[a.length];
int[] dpRight = new int[a.length];
int[] arr = new int[a.length];
dpLeft[0] = 1;
dpRight[0] = 1;
for (int i = 1; i < a.length; i++) {
dpLeft[i] = dpLeft[i - 1] * a[i - 1];
dpRight[i] = dpRight[i - 1] * a[a.length - i];
}
for (int i = 0; i < a.length; i++) {
arr[i] = dpLeft[i] * dpRight[a.length - i - 1];
}
return arr;
}
}