自己想的办法超时了,下面是大神题解
public int[] constructArr(int[] a) {
if(a == null || a.length == 0)
return new int[0];
int len = a.length;
int[] resLeft = new int[len];
int[] b = new int[len];
resLeft[0] = 1;//左边无元素,设置初始值为1
for (int i = 1; i < len; i++) {
resLeft[i] = a[i - 1] * resLeft[i - 1];
}
int[] resRight = new int[len];
resRight[len - 1] = 1;//右边无元素,设置初始值为1
for (int i = len - 2; i >= 0; i--) {
resRight[i] = resRight[i + 1] * a[i + 1];
}
for (int i = 0; i < len; i++) {
b[i] = resLeft[i] * resRight[i];
}
return b;
}
resLeft数组:数组元素resLeft[i]代表i左边所有元素(不含i)的乘积
resRight数组:数组元素resRight[i]代表i右边所有元素(不含i)的乘积
题解作者leefcode网址:https://leetcode.cn/u/fomalhaut1998/