LeetCode Product of Array Except Self

來源:互聯網
上載者:User

標籤:

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

思路分析:基本思路是用兩個數組left和right,left儲存從最左側到當前數之前的所有數位乘積,right儲存從最右側到當前之後的所有數位乘積,然後,結果數組就是把這兩個數組對應位置相乘即可。如果想只是用O(1)的space,就需要複用輸入和輸出數組的空間,基本思路是,先計算right數組,利用result數組的空間儲存,然後計算left數組,只需要一個變數left儲存當前從最左側到當前數字之前的所有數字之和。總之,使用好輸入輸出數組的空間,避免使用更多space。以下注釋部分code給出了O(n) 空間複雜度的解法,非注釋部分給出了O(1)空間複雜度的解法。時間複雜度就是O(n)。

AC Code:

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


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

LeetCode Product of Array Except Self

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.