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].python
Solve it without division and in O(n).數組
For example, given [1,2,3,4], return [24,12,8,6].code
簡單來講就是對於數組中每一項,求其餘項之積。element
恭喜你,你超時了。it
要仔細考慮元素爲零的狀況。io
直接除下去。class
零的位置對應值爲其餘元素之積,其餘位置爲零。import
所有都是零。lambda
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
遇事多思考,輕易不要循環。