构建乘积数组
构建乘积数组
http://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46
链接:https://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46?answerType=1&f=discussion 来源:牛客网 给定一个数组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];)
import java.util.ArrayList; public class Solution { public int[] multiply(int[] A) { //上下三角算法,Bi对角线初始化为1 int len = A.length; int[] B = new int[len]; B[0] = 1; for(int i=1;i<len;i++){ B[i] = B[i-1] * A[i-1]; } int temp=1; for(int i=len-2;i>=0;i--){ temp = temp * A[i+1]; B[i] = B[i] * temp; } return B; } }