剑指offer 数组中出现次数超过一半的数字

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

Solution

hash表保存数字出现次数,对字典排序即可。

import math
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        if len(numbers) == 0:
            return 0
        hashmap = {}
        for elmt in numbers:
            if elmt in hashmap:
                hashmap[elmt] += 1
            else:
                hashmap[elmt] = 1
        res = sorted(hashmap.items(), key=lambda e: e[1], reverse=True)
        if res[0][1] > math.ceil(len(numbers)//2):
            return res[0][0]
        else:
            return 0

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章