51、構建乘積數組
阿新 • • 發佈:2017-08-31
list cnblogs 其中 使用 bsp span [] != i++
一、題目
給定一個數組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]。不能使用除法。
二、解法
1 import java.util.ArrayList; 2 public class Solution { 3 public int[] multiply(int[] A) { 4 int len = A.length; 5 int[] B = new int[len]; 6 if(len != 0){7 B[0] = 1; 8 //計算下三角連乘 9 for(int i = 1; i < len; i++) 10 B[i] = B[i-1]*A[i-1]; 11 int temp = 1; 12 //計算上三角 13 for(int j = len - 2; j >=0; j--){ 14 temp *= A[j+1];15 B[j] *= temp; 16 } 17 } 18 return B; 19 } 20 }
51、構建乘積數組