[Leetcode]238. Product of Array Except Self
阿新 • • 發佈:2017-11-28
output all exc without pro integer put num rod
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.)
思路:不能用除法,只能用乘法。對於每個位置,最後的結果是他左邊的所有數的積乘上右邊所有數的積,
比如,對於 3 這個數, 他這個位置上最後的結果為 8 。8 是左邊 [ 1, 2 ] 和 右邊 [ 3 ] 的乘積。那麽我們可
以先反向遍歷數組,得到每個位置上相對應的右邊的乘積。先初始化一個結果數組[ 1, 1, 1, 1 ]。執行一次
的結果為 [ 24, 12, 4, 1],再正向遍歷一次,得到最後的結果為 [24,12,8,6]
.
class Solution { public int[] productExceptSelf(int[] nums) {int n = nums.length; int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = 1; int product = 1; for (int i = 0; i < n; i++){ res[i] *= product; product *= nums[i]; } product = 1; for (int i = n-1; i>=0; i--){ res[i]*= product; product *= nums[i]; } return res; } }
[Leetcode]238. Product of Array Except Self