找水王

思路:水王发的帖子最多,所以两个两个抵消,最后剩下的那个一定是水王的帖子

下面是c++程序

#include <iostream>

using namespace std;

typedef int  DataType;

DataType FindKing(DataType* ID, int n)

{

    DataType candidate;

    int nTime, i;

    nTime = 0;

    for (int i = 0; i<n; i++)

    {

        if (nTime == 0)

        {

            candidate = ID[i];

            nTime = 1;

        }

        else

        {

            if (candidate == ID[i])

                nTime++;

            else

                nTime--;

        }

    }

    return candidate;

}

int main()

{

    DataType ID[10] = { 1, 1, 1, 1, 1, 2, 3, 4, 5, 1 };

    cout << "水王是:"<<FindKing(ID, 10) << endl;

    return 0;

}

 

 

posted on 2019-01-10 10:24  数理小牛  阅读(83)  评论(0编辑  收藏  举报

导航