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

Input:

  • 數組 :: int[]

Output:

  • 每一位存除這個數以外其他數的乘積 :: int[]

Intuition:

用constant的space,還有比這更露骨的提示嘛?除了two pointers 還能想到啥。左邊的指針掃一遍,把每個數左邊的乘積搞定,右邊指針右邊掃一遍,把右邊的乘積搞定就OK了。

但素,我居然還是卡住了,數學不好的同學們,還是要寫幾個case確定你的關系式是正確的,兩邊的margin要處理正確。

public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int len = nums.length;
        int left = nums[0];
        res[0] = 1;
        //find product on the left side
        for (int i = 1; i < len; i++){
            res[i] = left;
            left *= nums[i];
        }
        
         //find product on the right side and multipy it with left side product
        int right = nums[nums.length - 1];
        for (int i = len - 2; i >= 0; i--){
            res[i] *= right;
            right *= nums[i];
        }
        return res;
    }

Reference

https://leetcode.com/problems/product-of-array-except-self/description/

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

推薦閱讀更多精彩內容