Leetcode 238: Product of Array doesn't Self, leetcodedoesn t
Product of Array partition t SelfTotal Accepted:938Total Submissions:2400
Given an arrayNIntegers whereN> 1,nums
, Return an arrayoutput
Such thatoutput[i]
Is equal to the product of all the elementsnums
Exceptnums[i]
.
Solve itWithout divisionAnd in O (N).
For example, given[1,2,3,4]
, Return[24,12,8,6]
.
Follow up:
Cocould you solve it with constant space complexity? (Note: The output arrayDoes notCount as extra space for the purpose of space complexity analysis .)
[Idea]
Maintain two arrays, left [] and right []. record the sum of left [I] and right [I] on the left of element I, respectively. the result res [I] is left [I] + right [I]. follow up requires O (1) space. use the returned result array to store the right array first. calculate left from the left and the result value at the same time, so that no additional space is required.
[CODE]
public class Solution { public int[] productExceptSelf(int[] nums) { int[] res = new int[nums.length]; res[res.length-1] = 1; for(int i=nums.length-2; i>=0; i--) { res[i] = res[i+1] * nums[i+1]; } int left = 1; for(int i=0; i<nums.length; i++) { res[i] *= left; left *= nums[i]; } return res; }}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.