Moore's voting algorithm

算法的基本思想

这个算法是解决这样一个问题:从一个数组中找出出现半数以上的元素。他的基本思想是:每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。

算法的实现

 1 int majorityElement(vector<int> &num)
 2 {
 3     int curIdx = 0, count = 1;
 4     for (int i = 1; i < num.size(); ++i)
 5     {
 6         num[i] == num[curIdx] ? ++count : --count;
 7         if (!count)
 8         {
 9             curIdx = i;
10             count = 1;
11         }
12     }
13 
14     return num[curIdx];
15 }

 

posted @ 2016-09-13 14:50  BelFuture  阅读(604)  评论(0编辑  收藏  举报
The horizon of life is broadened chiefly by the enlargement of the heart.