[leetcode] Product of Array Except Self

來源:互聯網
上載者:User

標籤:lin   public   pre   nal   interview   you   visio   ...   pts   

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

分析:題目翻譯一下: 要求計算一個數組中,除了自己本身之外的所有元素的乘積,不能使用除法。光看要求,不看限制,我們有兩個思路:1、計算所有元素的乘積product,然後從頭到尾遍曆,對於任意的i,res[i] = product / nums[i]。      這當然是最一般的方法,但是不能用除法,這個方法就忽略了。2、加入我們計算i位置的結果res[i],實際就是計算res[i]=nums[0]*nums[1]*...*nums[i-1]*nums[i+1]*...*nums[nums.length-1]     下面就是玄學:     res[i]=nums[0]*nums[1]*...*nums[i-1]*nums[i+1]*...*nums[nums.length-1]=(nums[0]*nums[1]*...*nums[i-1])*(nums[i+1]*...*nums[nums.length-1])        也就是將結果分成兩個部分,left和right,所以res[i]=left[i]*right[i],下面就是找如何確定left和right數組。     left[i]=nums[0]*nums[1]*...*nums[i-1],這就是一個遞迴嘛。,left[i]=left[i-1]*nums[i-1]代碼如下:
 1 class Solution { 2     public int[] productExceptSelf(int[] nums) { 3         int n = nums.length; 4  5         int[] left = new int[n]; 6         left[0] = 1; 7         for ( int i = 1 ; i < n ; i ++ ) 8             left[i] = left[i-1] * nums[i-1]; 9 10         int[] right = new int[n];11         right[n-1] = 1;12         for ( int i = n-2 ; i >= 0 ; i -- )13             right[i] = right[i+1] * nums[i+1];14         15         int[] res = new int[n];16         for ( int i = 0 ; i < n ; i ++ )17             res[i] = left[i] * right[i];18         19         return res;20     }21 }

    已耗用時間1ms,擊敗100%。

但是這個方法還是用到了多餘的空間,題目說希望可以不使用多餘的空間。因此可以用一個right變數來代替從右向左的那次遍曆。

參考discuss大神的代碼:

 1 public int[] productExceptSelf(int[] nums) { 2     int n = nums.length; 3     int[] res = new int[n]; 4     res[0] = 1; 5     for (int i = 1; i < n; i++) { 6         res[i] = res[i - 1] * nums[i - 1]; 7     } 8     int right = 1; 9     for (int i = n - 1; i >= 0; i--) {10         res[i] *= right;11         right *= nums[i];12     }13     return res;14 }

 

 

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