Leetcode238. Product of Array Except Self

Leetcode238. Product of Array Except Self

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

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

思路

使用左邊乘積和右邊乘積進行計算。

給定數組[2、3、4、5],對於數字4來說它的結果是2 * 3 * 5,即位於4左邊的乘積2*3乘上位於4右邊的乘積5。用這個思想我們遍歷兩邊nums[]數組,記錄下每個元素的左右乘積。

Numbers:     2    3    4     5
Lefts:            2  2*3 2*3*4
Rights:  3*4*5  4*5    5     

用1填充空餘的位置

Numbers:     2    3    4     5
Lefts:       1    2  2*3 2*3*4
Rights:  3*4*5  4*5    5     1

時間複雜度O(n)

public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] res = new int[n];
    // Calculate lefts and store in res.
    int left = 1;
    for (int i = 0; i < n; i++) {
        if (i > 0)
            left = left * nums[i - 1];
        res[i] = left;
    }
    // Calculate rights and the product from the end of the array.
    int right = 1;
    for (int i = n - 1; i >= 0; i--) {
        if (i < n - 1)
            right = right * nums[i + 1];
        res[i] *= right;
    }
    return res;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章