LeetCode 刷題筆記 之 數組自乘

題目如下:

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

解法如下:

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int a[]=new int[nums.length];
        int b[]=new int[nums.length];
        int c[]=new int[nums.length];
        a[0]=1;b[nums.length-1]=1;
        for(int i=1;i<nums.length;i++){//構建兩個數組{對於數組[a0,a1,a2,a3]而言}
            a[i]=nums[i-1]*a[i-1];//第一個是[1,a0,a0*a1,a0*a1*a2]
            b[nums.length-i-1]=nums[nums.length-i]*b[nums.length-i];//第二個是[a1*a2*a3,a2*a3,a3,1]
        }
        for(int i=0;i<nums.length;i++){
            c[i]=a[i]*b[i];//則這兩個數組相乘的結果即爲所求
        }
        return c;
        
    }
}

發佈了38 篇原創文章 · 獲贊 5 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章