Given an array A [0, 1,…, n – 1), please build an array B [0, 1,…, n – 1), including the elements in the B B = [I] A [0] x [1] by A… [I – 1) * A * A [I + 1) *… X] [n – 1 A. You can’t use division.

Example:

Input: [1,2,3,4,5] output: [120,60,40,30,24]

Tip:

The sum of the product of all elements does not overflow the 32-bit integer A.length <= 100000

java

// class Solution {
// public int[] constructArr(int[] a) {
        
// int[] res = new int[a.length];

// int math =0;
// int sum = 1;
// for(int j =0; j
// if(a[j]==0) math++;
// sum = sum*a[j];
                
/ /}
// if(math>1) return res;



// for(int i=0; i
// if(a[i]==0){
// int number = 1;
// for(int j =0; j
// if(j! =i) number = number*a[j];
                
/ /}
// res[i] = number;
/ /}
// else{
// res[i] =(int)(sum*Math.pow(a[i],-1));
/ /}
/ /}
// return res;
/ /}
// }
class Solution {
    public int[] constructArr(int[] a) {
        int[] ans = new int[a.length];
        for (int i = 0, p = 1; i < a.length; i++) {
            ans[i] = p;
            p *= a[i];
        }
        for (int i = a.length - 1, p = 1; i >= 0; i--) {
            ans[i] *= p;
            p *= a[i];
        }
        returnans; }}Copy the code

The first loop takes the product before the ith position, and the second loop takes the product after the ith position and multiplies it with the previous one.