首页 > 编程语言 > 详细

Boyer-Moore 多数投票算法

时间:2021-08-03 10:17:42      阅读:18      评论:0      收藏:0      [点我收藏+]

题目(模板)

给定一个序列,找出这个序列中是否有一个数字出现的次数超过数组长度的一半,若有输出这个数
Leetcode169

样例

Input

16
7 7 5 7 5 1 5 7 5 5 7 7 7 7 7 7

Output

7

思路

维护一个临时众数 \(candidate\) 和它出现的此时 \(count\)
初始设 \(candidate\) 为任意值(为方便可以设其为第1个数)、\(count\)\(0\)
遍历 \(a\) 中的所有元素,对于每个元素,如果在 \(x\) 之前,\(count\) 的值为 \(0\) 那么 \(candidate=x\)
然后判断\(x\)

  • \(x\)\(candidate\) 相等, \(count\) 就+1
  • \(x\)\(candidate\) 不相等, \(count\) 就-1
nums:       [7, 7, 5, 7, 5, 1 | 5, 7 | 5, 5, 7, 7 | 7, 7, 7, 7]
candidate:   7  7  7  7  7  7   5  5   5  5  5  5   7  7  7  7
count:       1  2  1  2  1  0   1  0   1  2  1  0   1  2  3  4

最后的 \(candidate\) 就是答案

代码

  int n;
  cin>>n;
  for(int i=1;i<=n;i++)
    cin>>a[i];
  int candidate=a[1],count=1;
  for(int i=2;i<=n;i++)
  {
    if(count==0)
      candidate=a[i];
    if(a[i]==candidate)
      count++;
    else
      count--;
    //cout<<candidate<<" "<<count<<endl;
  }
  cout<<candidate<<endl;

Boyer-Moore 多数投票算法

原文:https://www.cnblogs.com/a-little-mushroomspy/p/15092353.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!