劍指offer66 構建乘積數組

題目鏈接
給定一個數組 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]。不能使用除法。

示例:

輸入: [1,2,3,4,5]
輸出: [120,60,40,30,24]

提示:

所有元素乘積之和不會溢出 32 位整數
a.length <= 100000

題解:
因爲題目中說明了不準使用除法,所以這裏利用對稱關係,經過兩次遍歷得到計算結果
題解鏈接1
題解鏈接2

//因爲題目中說明了不準使用除法,所以這裏利用對稱關係,經過兩次遍歷得到計算結果
class Solution {
    public int[] constructArr(int[] a) {
        if(a==null || a.length == 0){
            return new int[]{};
        }
        int[] res = new int[a.length];
        int left =1;
        for(int i=0;i<res.length;i++ ){
            res[i] = left;
            left *= a[i];
        }
        int right= 1;
        for(int i=res.length-1;i>=0;i--){
            res[i] *= right;
            right*=a[i];
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章