Moore's voting algorithm
来源:互联网 发布:芜湖炎黄网络 编辑:程序博客网 时间:2024/05/20 04:29
注:
若从数组中找出出现大于1/3元素个数的元素。
则:有2(3-1)个候选者,3个不同的数字抵消。剩下的候选者统计个数,若大于1/3元素个数则取出。代码最后面贴出。
若从数组中找出出现大于1/k元素个数的元素。
则:有k-1个候选者,k个不同的数字抵消。剩下的候选者统计个数,大于1/k元素个数的取出。
转载自:http://blog.csdn.net/chfe007/article/details/42919017
最近在刷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
- 从GITLAB误删除数据库想到的
- 17/2/3/ 兄弟郊游问题
- 【t013】无聊的军官
- poj 1789 Truck History(prim)
- React Native
- Moore's voting algorithm
- docker使用阿里云Docker镜像库加速(修订版)
- json:创建一个对象,其它一个属性是数组;创建一个对象,使用function作为属性值
- 转-Redis常见的性能问题都有哪些?如何解决?
- 空闲时间学一个Linux命令(17)—— whereis命令
- MySQL日期时间函数大全
- RN4_JS(react native 学习)
- 前言,聊一聊想法
- 关于命名实体识别