找水王(2)

   求解和第一次很相似,相同的思路进行求解即可。同时删除4个不同的ID后,剩余数据中3个多数id仍然是多数ID。

上题只需要一个结果,而现在需要3个结果,上题用到的nTimes,也应改为3个计数器。现在我们需要3个变量来记录当前遍历过的 3个不同的ID,而nTimes的3个元素分别对应当前遍历过的3个ID出现的个数。如果遍历中有某个ID不同于这3个当前ID,我们就判断当前3个ID 是否有某个的nTimes为0,如果有,那这个新遍历的ID就取而代之,并赋1为它的遍历数(即nTimes减1),如果当前3个ID的nTimes皆不 为0,则3个ID的nTimes皆减去1。

#include<iostream>
using namespace std;
typedef int Type;

void Find(int * ID, int n)
{
    int candidate[3];
    int nTimes[3] = { 0 };
    int i;

    for (i = 0; i < n; i++)
    {
        if (nTimes[0] == 0)
        {
            if (ID[i] == candidate[1])
                nTimes[1]++;
            else if (ID[i] == candidate[2])
                nTimes[2]++;
            else
            {
                candidate[0] = ID[i];
                nTimes[0]++;
            }
        }
        else if (nTimes[1] == 0)
        {
            if (ID[i] == candidate[0])
                nTimes[0]++;
            else if (ID[i] == candidate[2])
                nTimes[2]++;
            else
            {
                candidate[1] = ID[i];
                nTimes[1]++;
            }
        }
        else if (nTimes[2] == 0)
        {
            if (ID[i] == candidate[0])
                nTimes[0]++;
            else if (ID[i] == candidate[1])
                nTimes[1]++;
            else
            {
                candidate[2] = ID[i];
                nTimes[2]++;
            }
        }
        else
        {
            if (ID[i] == candidate[0])
                nTimes[0]++;
            else if (ID[i] == candidate[1])
                nTimes[1]++;
            else if (ID[i] == candidate[2])
                nTimes[2]++;
            else
                nTimes[0]--, nTimes[1]--, nTimes[2]--;
        }
    }
    cout << "三个水王的id是" << candidate[0] << " " << candidate[1] << " " << candidate[2] << " " << endl;
    return;
}

int main()
{
    Type ID[] = { 1,1,1,1,1,1,6,6,6,6,6,3,3,3,3,3,3,4,4,5 };
    Find(ID, 20);
    return 0;
}

 

原文地址:https://www.cnblogs.com/lyhao/p/5540489.html