劍指offer 52題 【數組】 構建乘積數組

題目描述

給定一個數組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、c,b數組從左至右計算,c數組從右至左計算。
思路二:
如思路一,省略倆個數組。

代碼一:
public class Title52 {
	public int[] multiply(int[] a) {
		if(a == null || a.length == 0)
			return a;
		// 初始化
		int[] b = new int[a.length];
		int[] c = new int[a.length];
		int[] res = new int[a.length];
		
		for(int i=0;i<res.length;i++)
			res[i] = 1;
		
		b[0] = a[0];
		c[a.length-1] = a[a.length-1];
		for(int i=1;i<a.length;i++){
			b[i] = b[i-1] * a[i];
		}
		
		for(int i=a.length-2;i>0;i--){
			c[i] = c[i+1] * a[i];
		}
		
		for(int i=0;i<a.length;i++){
			if(i-1 >=0)
				res[i] *= b[i-1];
			if(i+1 <= a.length -1)
				res[i] *= c[i+1];
		}
		
		return res;
    }
	
	public static void main(String[] args) {
		int[] a = {1,2,3,4,5};
		int[] res = new Title52().multiply(a);
		for(int i =0;i<res.length;i++)
			System.out.print(res[i]+" ");
	}
}


代碼二:
public class Title52 {
    public int[] multiply(int[] A) {
        if(A == null || A.length == 0)
            return A;
        
        int[] B = new int[A.length];
        
        int product = 1;
        for(int i =0;i<A.length;i++){
            B[i] = product;
            product *= A[i];
        }
        
        product = 1;
        for(int i=A.length-1;i>=0;i--){
            B[i] *= product;
            product *= A[i];
        }
        
        return B;
    }
    
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5};
        int[] b = new Title52().multiply(a);
        for(int num : b){
            System.out.print(num + " ");
        }
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章