原题:
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.)
这是一道难度系数中等的题但是accept rate很高,题主愚钝,卡了好一会。题目要求不能用除法,对时间和空间的复杂度都有要求。代码如下:
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
size=len(nums)
output=[1]*size
output[0]=1
for i in range(1,size):
output[i]=output[i-1]*nums[i-1] #calculate the multiplication of all the left nums of nums[i]
temp=1
for j in range(size-1,-1,-1):
output[j]*=temp
temp*=nums[j] # the multiplication of all the right nums of nums[j]
return output