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.)
这题我认为是相当有难度的一道题,因为一是不能用除法,而是时间复杂度得是O(n),三是空间复杂度还得还是O(1),我自己是真做不出来,后来上网看了别人的做法,心里不禁感慨:妙啊!
代码如下:
class Solution(object):
def productExceptSelf(self, nums):
n = len(nums)
res = [1] * n
temp = 1
for i in range(0, n - 1):
res[i + 1] = res[i] * nums[i]
for i in range(n - 1, 0, -1):
res[i] *= temp
temp *= nums[i]
res[0] = res[0] * temp
return res
假定返回的数组是res,那么res[ i ] = left [ i ] * right [ i ],其中left[ i ] 是 nums [ i ] 左边所有数的乘积,right[ i ] 是 nums [ i ] 右边所有数的乘积。
因为说了返回的数组不算进空间复杂度里,那么我们可以先用res来存left,然后从nums的右边开始遍历,一个个算出right的值,然后乘上对于的left的值(之前保存在res中),这样时间复杂度降为O(n),空间复杂度为O(1)(只用了一个额外的变量)。