Lintcode46 Majority Number solution 题解

题目描述】

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

Notice:You may assume that the array is non-empty and the majority number always exist in the array.

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。

注意:你可以假设数组中没有非空和主元素。

【题目链接】

http://www.lintcode.com/en/problem/majority-number/

【题目解析】

最直观的想法就是,建立HashMap,记录list中的每一个integer元素的个数,如果大于1/2 list长度,即可返回。

进一步分析发现,其实并不需要记录所有的integer元素的个数,可以只记录当前最多的那一个majority。这种方法也称为: Boyer–Moore majority vote algorithm

换一种角度,是否可以直接从list中读取这个majority呢?如果对list进行排序,那么1/2处的元素,也就是majority的那个integer了。当然这种方法有个问题,就是对于没有majority的情况下(没有一个达到了1/2 总长度),是无法判断是否存在majority的,如果题目中明确一定存在这样的majority,那么这种方法也是可行的。

时间 O(n), 空间 O(1)

【参考答案】

http://www.jiuzhang.com/solutions/majority-number/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值