51、构建乘积数组

一、题目

给定一个数组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 }

 

posted @ 2017-08-31 19:55  fankongkong  阅读(190)  评论(0编辑  收藏  举报