【剑指Offer】28.数组中出现次数超过一半的数字(Python实现)

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为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
        mirrors = {}
        for i in numbers:
            if i in mirrors.keys():
                mirrors[i] += 1
            else:
                mirrors[i] = 1
            if mirrors[i] > len(numbers)/2:
                return i
        return 0
发布了60 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36936730/article/details/104668431