1. 程式人生 > >[LeetCode] Product of Array Except Self 除本身之外的陣列之積

[LeetCode] Product of Array Except Self 除本身之外的陣列之積

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].

Follow up:
Could you solve it with constant space complexity? (Note: The output array does not

count as extra space for the purpose of space complexity analysis.)

這道題給定我們一個數組,讓我們返回一個新陣列,對於每一個位置上的數是其他位置上數的乘積,並且限定了時間複雜度O(n),並且不讓我們用除法。如果讓用除法的話,那這道題就應該屬於Easy,因為可以先遍歷一遍陣列求出所有數字之積,然後除以對應位置的上的數字。但是這道題禁止我們使用除法,那麼我們只能另闢蹊徑。我們想,對於某一個數字,如果我們知道其前面所有數字的乘積,同時也知道後面所有的數乘積,那麼二者相乘就是我們要的結果,所以我們只要分別創建出這兩個陣列即可,分別從陣列的兩個方向遍歷就可以分別創建出乘積累積陣列。參見程式碼如下:

C++ 解法一:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> fwd(n, 1), bwd(n, 1), res(n);
        for (int i = 0; i < n - 1; ++i) {
            fwd[i + 1] = fwd[i] * nums[i];
        }
        
for (int i = n - 1; i > 0; --i) { bwd[i - 1] = bwd[i] * nums[i]; } for (int i = 0; i < n; ++i) { res[i] = fwd[i] * bwd[i]; } return res; } };

Java 解法一:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        int[] fwd = new int[n], bwd = new int[n];
        fwd[0] = 1; bwd[n - 1] = 1;
        for (int i = 1; i < n; ++i) {
            fwd[i] = fwd[i - 1] * nums[i - 1];
        }
        for (int i = n - 2; i >= 0; --i) {
            bwd[i] = bwd[i + 1] * nums[i + 1];
        }
        for (int i = 0; i < n; ++i) {
            res[i] = fwd[i] * bwd[i];
        }
        return res;
    }
}

我們可以對上面的方法進行空間上的優化,由於最終的結果都是要乘到結果res中,所以我們可以不用單獨的陣列來儲存乘積,而是直接累積到res中,我們先從前面遍歷一遍,將乘積的累積存入res中,然後從後面開始遍歷,用到一個臨時變數right,初始化為1,然後每次不斷累積,最終得到正確結果,參見程式碼如下:

C++ 解法二:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> res(nums.size(), 1);
        for (int i = 1; i < nums.size(); ++i) {
            res[i] = res[i - 1] * nums[i - 1];
        }
        int right = 1;
        for (int i = nums.size() - 1; i >= 0; --i) {
            res[i] *= right;
            right *= nums[i];
        }
        return res;
    }
};

Java 解法二:

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

參考資料: