leetcode-238. Product of Array Except Self

238. 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.)


題意:

給定一個數組nums,結果返回另一個數組outputoutput[i]nums 數組裏除了 nums[i] 元素的其他元素的積。

(是否能使時間複雜度爲 O(n)


題解:

自己一開始的想法是先求出 nums 裏所有元素的積 product,在用product/nums[i] 作爲 output[i]

但是提交會發現 [0,0] ,[1,0] 等情況就會出現 除0 等異常,而且邊界情況太多,單獨考慮太麻煩,應該就是方法有問題。



看了 discuss 的方法,發現真是巧妙:

n = nums.length 

對於結果output數組,先使output[i] 等於 nums 的前 i-1 個元素的積,則output的最後一個元素的就爲所求的結果。

而對於前 n -1 個元素,output[i] 應該等於  output[i] * (後面 n - i 個元素的積)


例如:

第一遍循環:   (output[0]= 1)                   

nums:    [ 1 , 2 , 3 , 4 , 5]

output:   [ 1, 1 , 2 , 6 , 24]

第二遍循環:

Output[5]= output[5]  (24

Output[4]= output[4] * nums[5] (即6*5

Output[3]= output[3] * nums[5]*nums[4] (即2 *5 *4

…  


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


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