Moore's voting algorithm
来源:互联网 发布:vue.js input不可编辑 编辑:程序博客网 时间:2024/05/23 21:05
最近在刷LeetCode的题的时候,发现一个特别巧妙的算法:Moore’s voting algorithm。
这个算法是解决这样一个问题:从一个数组中找出出现半数以上的元素。
Moore的主页上有这个算法的介绍:A Linear Time Majority Vote Algorithm和这个算法的一个简单示例演示:演示链接。
算法的基本思想
每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。
当然,最后剩下的元素也可能并没有出现半数以上。比如说数组是[1, 2, 3],最后剩下的3显然只出现了1次,并不到半数。排除这种false positive情况的方法也很简单,只要保存下原始数组,最后扫描一遍验证一下就可以了。
算法的实现
在算法执行过程中,我们使用常量空间实时记录一个候选元素c以及其出现次数f(c),c即为当前阶段出现次数超过半数的元素。
在遍历开始之前,该元素c为空,f(c)=0。
然后在遍历数组A时,如果f(c)为0,表示当前并没有候选元素,也就是说之前的遍历过程中并没有找到超过半数的元素。那么,如果超过半数的元素c存在,那么c在剩下的子数组中,出现次数也一定超过半数。因此我们可以将原始问题转化为它的子问题。此时c赋值为当前元素, 同时f(c)=1。
如果当前元素A[i] == c, 那么f(c) += 1。(没有找到不同元素,只需要把相同元素累计起来)
如果当前元素A[i] != c,那么f(c) -= 1。 (相当于删除1个c),不对A[i]做任何处理(相当于删除A[i])
如果遍历结束之后,f(c)不为0,那么元素c即为寻找的元素。上述算法的时间复杂度为O(n),而由于并不需要真的删除数组元素,我们也并不需要额外的空间来保存原始数组,空间复杂度为O(1)。
C++代码实现如下:
int majorityElement(vector<int> &num){ int curIdx = 0, count = 1; for (int i = 1; i < num.size(); ++i) { num[i] == num[curIdx] ? ++count : --count; if (!count) { curIdx = i; count = 1; } } return num[curIdx];}
- Moore's voting algorithm
- Moore’s voting algorithm
- Moore's voting algorithm
- Moore’s Voting Algorithm
- Moore's voting algorithm
- Moore's voting algorithm
- Moore's voting algorithm
- Majority Element解决:Moore's Voting Algorithm
- leetcode-169 Majority Element(Moore's voting algorithm)
- [LeetCode 169]Majority Element: Moore Voting Algorithm
- 153. Find Minimum in Rotated Sorted Array\229. Majority Element II\Moore's voting algorithm
- Moore's voting最大投票算法
- LeetCode Majority Element II(Moore Voting Algorithm即Majority Voting Algorithm)
- Moore's majority vote algorithm
- Boyer-Moore algorithm
- Boyer-Moore algorithm ---c++
- Boyer-Moore algorithm
- Boyer Moore Pattern Matching Algorithm
- Ubuntu中配置OpenCV
- xml javascript
- Keil C51详细设置及调试方法
- iOS中#import和@class的区别
- windows下一些启动服务的命令
- Moore's voting algorithm
- struct sockaddr与struct sockaddr_in区别
- C++标准库set类型
- 构建网站的20个技巧
- Android添加Flurry统计
- Java中,关于资源Resource的定位问题
- netty5.0源码解析 ByteBuf和相关辅助类
- ubuntu 上面安装 sqlitebrowser 的方法
- 关于oracle中PL/SQL语句,即存储过程的写法和调用。