多数投票算法 --- A linear time majority vote algorithm

来源:互联网 发布:福彩快3源码 编辑:程序博客网 时间:2024/05/29 04:38

算法文档原文:

A Linear Time Majority Vote Algorithm

This algorithm, which Bob Boyer and I invented in 1980 decides which element of a sequence is in the majority, provided there is such an element. How would you determine the majority element of:
sequence:  A A A C C B B C C C B C C
You could count the number of occurrences of each element. Here is how we do it, in one pass.

For details, see


A A A C C B B C C C B C C

We will sweep down the sequence starting at the pointer position shown above.

As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0.

When we move the pointer forward over an element e:

  • If the counter is 0, we set the current candidate to e and we set the counter to 1.
  • If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.
When we are done, the current candidate is the majority element, if there is a majority.

Click on Step below to carry out the algorithm.


中文算法解释:

算法思路:一旦两个相邻的元素不同,酒吧这两个元素对冲抵消掉。由于众数的出现频次大于数据其他元素出现频率次之和,所以这种抵消最后剩下的一定是众数


代码块:


for i in xrange(L):            if count == 0:                candidate = nums[i]                count += 1            else:                if nums[i] == candidate:                    count += 1                else:                    count -= 1



0 0
原创粉丝点击