デジタル実現のpythonの半分以上安全の発生を証明するために、[28]配列オファー

タイトル説明

この番号を見つけ、配列の半分以上の長さを表示される配列番号の数があります。例えば、入力アレイ9の長さは{1,2,3,2,2,2,5,4,2}。数2は5回、アレイ内のアレイの半分以上の長さ、出力2が表示されているので。0出力がある場合。

コード

ループのためのダブル

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        res = []
        for j in numbers:
            count = 0
            for n in numbers:
                if j == n:
                    count +=1
            res.append(count)
        result = max(res)
        if result <= len(numbers)/2:
            return 0
        else:
            index = res.index(result)
            return numbers[index]

s = Solution()
res = s.MoreThanHalfNum_Solution([1,2,3,2,2,2,5,4,2])
print(res)

解決する辞書

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        dict = {}
        for no in numbers:
            if not dict.has_key(no):
                dict[no] = 1
            else:
                dict[no] = dict[no] + 1
            if dict[no] > len(numbers)/2:
                return no
        return 0
公開された99元の記事 ウォンの賞賛6 ビュー3972

おすすめ

転載: blog.csdn.net/weixin_42247922/article/details/103996394