思路:设置两个数组pre,post;前者保存i之前的所有乘积,后者保存i之后的所有乘积;为了计算方便pre【0】=1;post【A.length-1】=1
那么B【i】=pre【i】*post【i】
public static int[] multiply(int[] A) {
if(A.length<2)return null;
int[] pre = new int[A.length];
pre[0]=1;
int[] post = new int[A.length];
post[A.length-1]=1;
int[] res = new int[A.length];
for (int i = 1; i <A.length ; i++) {
pre[i]=pre[i-1]*A[i-1];
}
for (int i = A.length-2; i>=0 ; i--) {
post[i]=post[i+1]*A[i+1];
}
for (int i =0;i<A.length;i++){
res[i]=pre[i]*post[i];
}
return res;
}
京公网安备 11010502036488号