构建乘积数组 --剑指offer

题目描述

给定一个数组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 static int[] multiply(int[] A) {
        long result=1;
        int len=A.length;
        int[] B = new int[len];
        if(len == 0 || A== null){
            return  A;
        }
        B[0] = 1;
        for(int i =1;i < len;i ++){
            B[i] = B[i-1]*A[i-1];
        }
        int tem=1;
        for(int i = len-2;i >=0 ;i --){
            tem *= A[i+1];
            B[i] *=tem;
        }
        return B;
    }

}

猜你喜欢

转载自www.cnblogs.com/nlw-blog/p/12460032.html