Lintcode46 Majority Number solution 题解
来源:互联网 发布:isis有多残忍知乎 编辑:程序博客网 时间:2024/06/14 21:40
【题目描述】
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/
- Lintcode46 Majority Number solution 题解
- Lintcode47 Majority Number II solution 题解
- Lintcode48 Majority Number III solution 题解
- Lintcode82 Single Number solution题解
- Lintcode83 Single Number ||solution 题解
- Lintcode84 Single Number |||solution 题解
- [LeetCode] Majority Element solution
- Majority Number
- Majority Number
- 169. Majority Element QuestionEditorial Solution
- 169. Majority Element QuestionEditorial Solution
- LintCode:Majority Number / Majority Number II / Majority Number III
- LeetCode题解:Majority Element
- LeetCode169. Majority Element题解
- LeetCode(169) Majority Number
- Lintcode - Majority Number II
- Lintcode - Majority Number III
- Majority Number II
- 配置MyBatis的整合遇到的问题
- Activity声明周期中七个回调方法中应该做的事情
- Ubuntu 彻底删除 MYSQL 然后重装 MYSQL
- Tomcat进程意外退出的问题分析
- Java线程(八):锁对象Lock-同步问题更完美的处理方式
- Lintcode46 Majority Number solution 题解
- Java生成不重复随机数UUID(转)
- hdu 1042 N! 高精度乘法
- IntelliJ-IDEA快捷键-常用
- HDU 4587 TWO NODES(割点 模板题)
- Git笔记
- 利用两个栈实现队列的--->基本操作
- python2.7和Python3.5的区别
- 泛型