构建乘积数组

来源:互联网 发布:mac安装xampp 编辑:程序博客网 时间:2024/06/07 03:17

题目描述

给定一个数组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]。不能使用除法。

import java.util.ArrayList;
public class Solution {
    public int[] multiply(int[] A) {
if(A==null || A.length==0){
            return null;
        }
        int len = A.length;
        int[] pre = new int[len];
        int[] back = new int[len];
        int[] res = new int[len];
        pre[0] = 1;
        back[0] = 1;
        for(int i=1; i<len; i++){
            pre[i] = A[i-1]*pre[i-1];
            back[i] = A[len-i]*back[i-1];
        }
        for(int i=0; i<len; i++){
            res[i] = pre[i]*back[len-i-1];
        }
        return res;
    }
}

0 0