238. Product of Array Except Self

Borris發表於2019-10-03

思路

/*
        The given conditions restrict serveral approach to the problem. First one disables us to calculate a product of all the numbers and divide it by each number itself. The second one disables us to have a brute force solution to solve the problem.
        Here is the O(n) solution:
        For each of the number, calculate its left and right product. Store them in left product array and right product array array respectively.
        Finally for each of the number i, multiply left[i] and right[i] to get the final result.
        */

解法一

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] results = new int[len];

        int[] left = new int[len];
        int[] right = new int[len];

        left[0] = 1; // Initialize the first element of left to be 1 cuz there is no number on the left of nums[0].
        // Calculate the left product
        for (int i = 1; i < len; i++) {
            left[i] = left[i - 1] * nums[i - 1];
        }

        right[len -1] = 1;
        for (int i = len - 2; i >= 0; i--) {
            right[i] = right[i + 1] * nums[i + 1];
        }

        for (int i = 0; i < len; i++) {
            results[i] = right[i] * left[i];
        }

        return results;
    }
}

解法二

上個解法的時間複雜度是 O(n), 空間複雜度也是 O(n)。這個解法的目的是為了減少空間複雜度到 O(1)。
既然我們已經能把一個數字左邊的乘法結果算出來,那麼可以將右邊的乘法結果直接乘到左邊的結果得出最終結果。
Keep tracking the product on the right of a number and keep updating the results.

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] results = new int[len];

        results[0] = 1; // Initialize the first element of left to be 1 cuz there is no number on the left of nums[0].
        // Calculate the left product
        for (int i = 1; i < len; i++) {
            results[i] = results[i - 1] * nums[i - 1];
        }

        int right = 1;
        for (int i = len - 1; i >= 0; i--) {
            results[i] = results[i] * right;
            right *= nums[i];
        }

        return results;
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章