题目: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]
解题思路:对于返回的数组product[]:
product[i]=nums[0]* nums[1]* …* nums[i-1]* nums[i+1]* nums[len(nums)-1]
所以,可以用两个循环进行计算:
第一个循环计算从nums[0]* …* nums[i-1]
第二个循环计算从nums[i+1]* …* nums[len(nums)-1]
代码:
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
product=[]
prv=1
# nums[0]*...*nums[i-1]
for i in range(len(nums)):
product.append(prv)
prv *=nums[i]
next=1
# nums[i+1]*...*nums[len(nums)-1)
for i in range((len(nums)-1),-1,-1): #倒序循环
product[i] =product[i]*next
next *=nums[i]
return product
代码2:超出了时间复杂度O(n)的要求:
product=[]
b=[]
for i in range(len(nums)):
b=nums[0:i]+nums[i+1:]
product.append(reduce(lambda x,y:x*y, b))
return product