题目描述
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * … * A[n-1],B[n-1] = A[0] * A[1] * … * A[n-2];)
参考思路
该题的题意就是求去掉A[i]的乘积,但是不能用除法。因此我们可以使用两个数组,pre保存i之前的成绩,post保存i之后的成绩,然后再对应相乘得到B[i]。
参考代码
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
int[] B = new int[A.length];
int[] pre = new int[A.length];
int[] post = new int[A.length];
pre[0] = 1;
post[A.length-1] = 1;
//pre数组中pre[i]存的是i之前的积
for(int i=1;i<A.length;i++){
pre[i] = pre[i-1] * A[i-1];
}
//post数组中post[i]存的是i之后的积
for(int i=A.length-2;i>=0;i--){
post[i] = post[i+1] * A[i+1];
}
//通过pre与post相乘即得到去掉A[i]之后的乘积
for(int i=0;i<A.length;i++){
B[i] = pre[i] * post[i];
}
return B;
}
}