【Python】LeetCode 238. Product of Array Except Self

題目描述

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

AC代碼

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

總結

遇事多思考,輕易不要循環。
相關文章
相關標籤/搜索