国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

【Python】LeetCode 238. Product of Array Except Self

kaka / 1706人閱讀

摘要:題目描述題目解析簡單來說就是對于數組中每一項,求其他項之積。算一遍全部元素的積再分別除以每一項要仔細考慮元素為零的情況。沒有零直接除下去。一個零零的位置對應值為其他元素之積,其他位置為零。兩個以上的零全部都是零。

題目描述

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].

題目解析

簡單來說就是對于數組中每一項,求其他項之積。

解題思路 對于每一項硬算其他項之積

恭喜你,你超時了。

算一遍全部元素的積再分別除以每一項

要仔細考慮元素為零的情況。

沒有零

直接除下去。

一個零

零的位置對應值為其他元素之積,其他位置為零。

兩個以上的零

全部都是零。

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
總結
遇事多思考,輕易不要循環。

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/45506.html

相關文章

  • 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].Solve it without division and in O(n). For...

    henry14 評論0 收藏0
  • [LeetCode] 238. Product of Array Except Self

    Problem 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 ...

    Loong_T 評論0 收藏0
  • 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]. Solve it without division and in O(n)....

    劉永祥 評論0 收藏0
  • [LeetCode] Product of Array Except Self

    Problem 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 ...

    golden_hamster 評論0 收藏0
  • [Leetcode] Product of Array Except Self 自身以外的數組乘積

    摘要:動態規劃復雜度時間空間思路分析出自身以外數組乘積的性質,它實際上是自己左邊左右數的乘積,乘上自己右邊所有數的乘積。所以我們可以用一個數組來表示第個數字前面數的乘積,這樣。同理,我們可以反向遍歷一遍生成另一個數組。 Product of Array Except Self Given an array of n integers where n > 1, nums, return an...

    rockswang 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<