剑指offer(二十九)之构建乘积数组

来源:互联网 发布:数据库实验报告总结 编辑:程序博客网 时间:2024/06/04 19:08
题目描述

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

思路分析:

用两层FOR循环,当i=j时,不做处理,否则进行累乘。代码简单,一看就懂。

代码:

<span style="font-family:SimSun;font-size:18px;">import java.util.ArrayList;public class Solution {    public int[] multiply(int[] A) {        int length=A.length;        int[] B=new int[length];        for(int i=0;i<length;i++){            int temp=1;            for(int j=0;j<length;j++){                if(i<j){                    temp*=A[j];                }else if(i==j){                                    }else{                    temp*=A[j];                }            }             B[i]=temp;        }        return B;    }}</span>


0 0