算法学习十八----寻找发帖水王

来源:互联网 发布:mac word文件丢失 编辑:程序博客网 时间:2024/04/30 14:34
题目:经常在论坛或者讨论区上面会看到一些人每个帖子都回复或者发了很多帖子(但是没有对其他用户有用途的)。现在写一个算法,找出发帖数目超过帖子总数的一半的用户ID--称为发帖水王。(注:本题假设发帖水王存在)
算法思路如下:
先对序列排序之后,计算出每个ID的次数,输出出现次数最大的用户ID即可。但是这个方法效率比较低。另一种方法,就是想办法将大问题转换成小问题,对列表进行扫描,每次删除两个不相同的ID,这样剩下的数中“水王”依然是出现次数超过总数的一半,然后不断重复这个过程,这样就可以通过O(N)的时间复杂度得到结果。

算法伪代码:

int FindWaterKing(int *arr, int n)//for i <- 0 to n     if nTimes == 0,means current number maybe the candidate          then assign arr[i] to candidate and add nTimes     else if candidate == arr[i]          then ++nTimes      else --nTimes

C++实现

int FindWaterKing(int *arr, int n){    int nTimes;//the number of current number    int candidate;//result    //for i <- 0 to n    for(int i = 0, nTimes = 0; i != n; ++i)    {        //if nTimes == 0,means current number maybe the candidate        if(nTimes == 0)        {            //then assign arr[i] to candidate and add nTimes            candidate = arr[i];            ++nTimes;        }        else        {            //if candidate == arr[i]            if(candidate == arr[i])            {                //then ++nTimes                ++nTimes;            }            else            {                //else --nTimes                --nTimes;            }        }    }    return candidate;}


0 0
原创粉丝点击