Topic links
https://leetcode.com/problems/product-of-array-except-self/
Original title
Given an array of n integers where n > 1, nums
and return an array such that's equal to the product of all output
output[i]
t He 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.)
Method of Thinking
Idea one
To facilitate the opening of ideas, not to consider the "follow up" requirements. The time complexity of O (n) is not possible with division, so multiplication cannot be done too much. Consider the first positive and negative two traversal, a traversal of each number to the left of the product of all numbers, a single traversal of each number to the right of the product of all numbers, the last two parts of the product multiplication is obtained.
The following code uses an additional two arrays, the spatial complexity of O (n).
Code
class solution(object): def productexceptself(self, nums): "" : Type Nums:list[int]: rtype:list[int] "" "Res, leftmul, Rightmul = [0]*len (Nums), [0]*len (Nums), [0]*len (nums) leftmul[0] = Rightmul[len (nums)-1] =1 forIinchXrange1, Len (nums)): leftmul[i] = leftmul[i-1] * nums[i-1] forIinchXrange (Len (nums)-2, -1, -1): rightmul[i] = rightmul[i+1] * nums[i+1] forIinchXrange (Len (nums)): res[i] = leftmul[i] * Rightmul[i]returnRes
Idea two
On the basis of the above, actually using the array to store the left and right product is not necessary, with temporary variables can be, so there is the following O (1) spatial complexity of the solution.
Code
class solution(object): def productexceptself(self, nums): "" : Type Nums:list[int]: rtype:list[int] "" "res = [0]*len (nums) tmp =1 forIinchXrange (Len (nums)): res[i] = tmp tmp *= nums[i] tmp =1 forIinchXrange (Len (nums)-1, -1, -1): Res[i] *= tmp tmp *= nums[i]returnRes
PS: Write wrong or write not clear please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/52071951
238. Product of Array Except Self [medium] (Python)