問題:
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.)
解答:
來自discussion里的解:
public int[] productExceptSelf(int[] nums) { int[] result = new int[nums.length]; //left side product result[0] = 1; for (int i = 1; i < nums.length; i++) { result[i] = result[i - 1] * nums[i - 1]; } //right side product int right = 1; for (int i = nums.length - 1; i >= 0; i--) { result[i] *= right; right *= nums[i]; } return result; }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/64934.html
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...
摘要:題目描述題目解析簡單來說就是對于數組中每一項,求其他項之積。算一遍全部元素的積再分別除以每一項要仔細考慮元素為零的情況。沒有零直接除下去。一個零零的位置對應值為其他元素之積,其他位置為零。兩個以上的零全部都是零。 題目描述 Given an array of n integers where n > 1, nums, return an array output such that o...
Problem 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 ...
Problem 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 ...
摘要:動態規劃復雜度時間空間思路分析出自身以外數組乘積的性質,它實際上是自己左邊左右數的乘積,乘上自己右邊所有數的乘積。所以我們可以用一個數組來表示第個數字前面數的乘積,這樣。同理,我們可以反向遍歷一遍生成另一個數組。 Product of Array Except Self Given an array of n integers where n > 1, nums, return an...
閱讀 1329·2021-11-15 11:37
閱讀 2214·2021-09-23 11:21
閱讀 1300·2019-08-30 15:55
閱讀 2105·2019-08-30 15:55
閱讀 2815·2019-08-30 15:52
閱讀 2819·2019-08-30 11:12
閱讀 1573·2019-08-29 18:45
閱讀 1885·2019-08-29 14:04