《编程之美》读书笔记(八):“发帖水王”扩展问题

感谢azuryy为大家分享他对《编程之美》的思考,以下是他对第2.3节“发帖水王”扩展问题提出的解题方法,原博客地址为: http://hi.baidu.com/azuryy/blog/item/65ecc2d5583c7ac151da4b15.html

 

Type candidate1 ;
Type candidate2;
Type candidate3;

void Find(Type* ID, int N)
{
    int nTimes1 = 0 ;
    int nTimes2 = 0 ;
    int nTimes3 = 0 ;
    int i;

    for( i = 0; i < N; i++)
    {
        if (nTimes1 == 0)
        {
            candidate1 = ID[i],nTimes1 = 1;
        }
        else
        {
            if (candidate1 == ID[i])
            {
                nTimes1++;
            }
            else
                if (nTimes2 == 0)
                {
                    candidate2 = ID[i],nTimes2 = 1;
                }
                else
                {
                    if (candidate2 == ID[i])
                    {
                        nTimes2++;
                    }
                    else
                    {
                        if (nTimes3 == 0)
                        {
                            candidate3 = ID[i], nTimes3 = 1;
                        }
                        else
                            if (candidate3 == ID[i])
                            {
                                nTimes3++;
                            }
                            else
                            {
                                nTimes1--;
                                nTimes2--;
                                nTimes3--;
                            }
                    }
                }
        }
    }
}

int main()
{
    int a[] = {0,4,1,4,0,4,1,4,1,0,3,3,0,3,3,3};
    Find(a,16);
    cout << candidate1 <<" " << candidate2 << " " << candidate3 << endl;
    return 0;
}

posted @ 2008-07-30 11:12  博文视点  阅读(2885)  评论(4编辑  收藏  举报