Leetcode - Product of Array Except Self

Paste_Image.png

My code:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length == 0)
            return null;
        int[] output = new int[nums.length];
        output[0] = 1;
        for (int i = 1; i < nums.length; i++)
            output[i] = output[i - 1] * nums[i - 1];
        
        int right = nums[nums.length - 1];
        for (int i = nums.length - 2; i >= 0; i--) {
            output[i] *= right;
            right *= nums[i];
        }
        
        return output;
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        int[] a = {1, 2, 3, 4};
        int[] b = test.productExceptSelf(a);
        for (int i = 0; i < b.length; i++)
            System.out.println(b[i]);
        
    }
}

My test result:

這次題目我沒做出來,因為實在想不出來有什么辦法可以在O(n) 下完成,而且不用除法,甚至所用空間是常熟的,除了輸出的數組。
網上查了才知道有個很巧妙地思想。
先用一個數組記錄下,從左乘到右的乘積。
再用一個數組記錄下,從右乘到左的乘積。
然后將兩個數組相乘作為輸出。

然后為了是空間變成常數級別。只用了一個數組。后期從右往左遍歷時,直接把乘數和原來的從左往右保存下來的乘積相乘。一樣的。
然后一些細節問題把握好就可以了。

**
總結: Array 這道題目的思想以前碰到過,從左往右遍歷下,再從右往左遍歷下,再合起來。可以避免平方級復雜度。
要留意了。
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length == 0)
            return null;
        int[] ret = new int[nums.length];
        ret[0] = 1;
        int mul = 1;
        /** from left to right */
        for (int i = 1; i < nums.length; i++) {
            mul *= nums[i - 1];
            ret[i] = mul;
        }
        
        /** from right to left */
        mul = 1;
        for (int i = nums.length - 2; i >= 0; i--) {
            mul *= nums[i + 1];
            ret[i] *= mul;
        }
        return ret;
    }
}

這次做還是沒有做出來。方法的確巧妙,我怎么就是想不到呢?我還依稀記得是分成兩邊乘,但就是忘了是這么處理的。

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        
        int n = nums.length;
        int[] ret = new int[n];
        ret[0] = 1;
        for (int i = 1; i < n; i++) {
            ret[i] = ret[i - 1] * nums[i - 1];
        }
        
        int right = 1;
        for (int i = n - 2; i >= 0; i--) {
            right = right * nums[i + 1];
            ret[i] = ret[i] * right;
        }
        
        return ret;
    }
}

這道題目還是沒想出來。主要考的就是這么個想法。
數組第i位記錄的是 [o, i -1]的乘積。
然后再從右往左。就可以了。

Anyway, Good luck, Richardo! -- 09/02/2016

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容