[Prove safety Offer] 66- Construction product array

topic

Given an array A [0,1, ..., n- 1], please construct an array B [0,1, ..., n- 1], where B is the element B [i] = A [ 0] A [. 1] ... A [-I. 1] A [I +. 1] ... A [n--. 1]. You can not use the division.

answer

  • Imagine the array constructed using a matrix B, B [i] is the i-th row in the matrix product of all the elements, and constructed befI afterI array, B [i] = befI [i] * afterI [i].
  • Construction befI afterI arrays top to bottom and bottom, respectively, the time complexity of O (n).
  • The overall time complexity of O (n).

Code

public class Main {
    public static void main(String[] args) {
        int[] A= {1,2,3,4,5};
        int[] B=multiply(A);
        for(int num:B) {
            System.out.println(num);
        }
    }
    
    public static int[] multiply(int[] A) {
        int len=A.length;
        int[] B=new int[len];
        int[] befI=new int[len];
        int[] afterI=new int[len];
        
        befI[0]=1;
        afterI[len-1]=1;
        for(int i=1;i<len;++i) {
            befI[i]=befI[i-1]*A[i-1];
        }
        for(int i=len-2;i>=0;--i) {
            afterI[i]=afterI[i+1]*A[i+1];
        }
        
        for(int i=0;i<len;++i) {
            B[i]=befI[i]*afterI[i];
        }
        return B;
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11142528.html