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].
简单来说就是对于数组中每一项,求其他项之积。
恭喜你,你超时了。
要仔细考虑元素为零的情况。
直接除下去。
零的位置对应值为其他元素之积,其他位置为零。
全部都是零。
class Solution(object):
def productExceptSelf(self, nums):
\"\"\"
:type nums: List[int]
:rtype: List[int]
\"\"\"
try:
from functools import reduce
finally:
pass
res = []
zeros = nums.count(0)
if zeros == 0:
product = reduce(lambda x, y: x * y, nums)
res = [product // x for x in nums]
elif zeros == 1:
now = nums[::]
pos = now.index(0)
del now[pos]
product = reduce(lambda x, y: x * y, now)
res = [0 if x != pos else product for x in range(len(nums))]
else:
res = [0] * len(nums)
return res
遇事多思考,轻易不要循环。