Product of Array Except self
Given an array of n integers where n > 1, nums
and return an array output
such that's equal to output[i]
th E 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 solve it with constant space complexity? (note:the output array does not count as extra space for the purpose of space complexity analysis.)
Solution:
The topic says not to use division and to produce results in linear time.
First, it is affected by the previous question to think about the bitwise operation, but the multiplication is not very fine.
So what if we scan it again to get the required array?
Think about what we can do when we traverse the Array, we can manipulate the position of the current rank, and the key is that we can also manipulate the constant position before and after the current rank.
Considering the currently traversed rank I, we can divide the process of ans[i] into two parts: one is the multiplication of all elements that are less than the rank of I, and the other is the multiplication of all elements that are greater than the rank of I.
It is not difficult to accomplish these two parts independently, as long as you iterate through it, use a variable to record the product (excluding the current element) of the element that has been traversed, and multiply it to ans[i].
And these two separate parts can also be synthesized by a traversal to complete, because as long as you know the entire length of the array to be traversed, from left to right and to the left is just a modulo problem.
The code is as follows:
1 classSolution:2 #@param {integer[]} nums3 #@return {integer[]}4 defproductexceptself (Self, nums):5n =Len (nums)6Ans = [1] *N7LEFT_FAC, RIGHT_FAC = 1, 18 forIinchrange (n):9Ans[i] *=LEFT_FACTenLEFT_FAC *=Nums[i] OneAns[n-i-1] *=RIGHT_FAC ARIGHT_FAC *= Nums[n-i-1] - returnAns
"Leetcode" Product of Array Except self