找出数组中的多数元素 [英] Find the majority element in array

查看:18
本文介绍了找出数组中的多数元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多数元素是出现超过数组大小一半的元素.

The majority element is the element that occurs more than half of the size of the array.

如何在O(n)中找到数组中的多数元素?

How to find the majority element in an array in O(n)?

示例输入:

{2,1,2,3,4,2,1,2,2}

预期输出:

2

推荐答案

多数元素(如果存在)也将是中位数.我们可以在 O(n) 中找到中位数,然后检查它是否确实是 O(n) 中的有效多数元素.更多实施细节link

The majority element (if it exists) will also be the median. We can find the median in O(n) and then check that it is indeed a valid majority element in O(n). More details for implementation link

这篇关于找出数组中的多数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆