• 找水王续


    题目:

    随着论坛的发展,管理员发现水王没有了,但是统计结果表明,有三个发帖很多的ID。据统计他们的发帖数量超过了1/4,你能从发帖列表中快速找到他们吗?

    思路:

    每次删除四个不同的ID(不管是否包含发帖数目超过总数1/4的ID),剩下的ID中,原发帖大于1/4的ID所占比例仍然大于1/4,不断重复这个过程,把ID列表中的ID总数降低。

    代码:

    #include<iostream>
    using namespace std;
    
    void Find(int ID[], int N, int candidate[])
    {
    	int nTimes[] = { 0,0,0 };
    	for (int i = 0; i<N; i++)
    	{
    		if (ID[i] == candidate[0])
    		{
    			nTimes[0]++;
    		}
    		else if (ID[i] == candidate[1])
    		{
    			nTimes[1]++;
    		}
    		else if (ID[i] == candidate[1])
    		{
    			nTimes[2]++;
    		}
    		else if (nTimes[0] == 0)
    		{
    			nTimes[0] = 1;
    			candidate[0] = ID[i];
    		}
    		else if (nTimes[1] == 0)
    		{
    			nTimes[1] = 1;
    			candidate[1] = ID[i];
    		}
    		else if (nTimes[2] == 0)
    		{
    			nTimes[2] = 1;
    			candidate[2] = ID[i];
    		}
    		else
    		{
    			nTimes[0]--;
    			nTimes[1]--;
    			nTimes[2]--;
    		}
    	}
    	cout<<"三个小水王ID是:";
    	for (int i = 0; i<3; i++)
    	{
    		cout<<candidate[i]<< " ";
    	}
    }
    
    void main()
    {
    	int ID[] = { 1,1,1,2,2,2,3,3,3,1,2,3,1,2,3,6 };
    	int N = 16;
    	int candidate[] = { -1,-1,-1 };
    
    	cout<<"发帖ID为:";
    	for (int i = 0; i<N; i++)
    	{
    		cout<<ID[i]<<" ";
    	}
    	cout << endl;
    	Find(ID, N, candidate);
    }
    

      运行结果:

  • 相关阅读:
    .net的25个小技巧
    使用ASP.Net2.0国际化你的网站祥解
    国外C#开源项目(转)
    千千阙歌
    js中var的有或无重复声明和以后的声明
    XMLHttpRequest
    java参数与引用
    Total Commander
    XMLDOM 的async属性
    Java内嵌类
  • 原文地址:https://www.cnblogs.com/zzcs/p/5608927.html
Copyright © 2020-2023  润新知