- 欢迎使用Markdown编辑器
- 题目
- 思路
- c++代码
你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。
题目扩展问题:
随着Tango的发展,管理员发现,“超级水王”没有了。统计结果表明,有3个发帖很多的ID,他们的发帖数目都超过了帖子总数目N的1/4。你能从发帖ID列表中快速找出他们的ID吗?
思路首先当只有一个水王,其发帖超过总数目的1/2的时候,采用以下思路
int candiate;
int Times = 1;
for i in 数组:
if(candiate == i) Times++;
else{
if(Times == 0){
candiate = i;
Times = 1;
}
else{
Times--;
}
}
那么首先当概率变成1/4的时候,也就意味着每四个数中这个数只需要出现一次,也就是当遇到和当前的数一样的时候,Times++ 就应该是+3,如果只需要求一位水王的话,思路如下:
int candiate;
int Times = 3;
for i in 数组:
if(candiate == i) Times += 3;
else{
if(Times == 0){
candiate = i;
Times = 3;
}
else{
Times--;
}
}
c++代码
// 寻找发帖水王-测试 #include#include using namespace std; // when initOrRandom is 1,it means this function is used to init, zero to random. void changeStoreData(int storeData[], const int totalLen, bool initOrRandom){ if(initOrRandom){ for(int i = 0; i < totalLen; i++){ storeData[i] = -1; } } else{ for(int i = 0; i < totalLen; i++){ if(storeData[i] == -1){ storeData[i] = rand(); } } } } void generateTestData(const int totalLen, int num,int storeData[],int leastTimes){ while(leastTimes){ int randomNum = rand()%totalLen; // 该位置没有存储数据 if(storeData[randomNum]==-1){ storeData[randomNum] = num; leastTimes--; } } } void printTestData(int storeData[], const int totalLen){ for(int i = 0; i < totalLen; i++){ cout< cout< int cntTimes[3] = {0}; shuiWang[0] = shuiWang[1] = shuiWang[2] = storeData[0]; for(int i = 1; i < totalLen; i++){ if(storeData[i] == shuiWang[0]){ cntTimes[0] += 3; } else if(storeData[i] == shuiWang[1]){ cntTimes[1] += 3; } else if(storeData[i] == shuiWang[2]){ cntTimes[2] += 3; } else if (cntTimes[0] == 0){ shuiWang[0] = storeData[i]; cntTimes[0] =3; } else if (cntTimes[1] == 0){ shuiWang[1] = storeData[i]; cntTimes[1] =3; } else if (cntTimes[2] == 0){ shuiWang[2] = storeData[i]; cntTimes[2] =3; } else { cntTimes[2] =0; cntTimes[1] =0; cntTimes[0] =0; } } } int main(){ srand(time(NULL)); // 设置随机数种子 const int totalLen = 200; int storeData[totalLen]; changeStoreData(storeData,totalLen,true); int leastTimes = totalLen/4 +1; // 产生三个不同的数 int num[3]; num[0] = rand(); do{ num[1] = rand(); }while(num[1] == num[0]); do{ num[2] = rand(); }while(num[2] == num[0] || num[2] == num[1]); // 生成数据 for(int i = 0; i < 3; i++){ generateTestData(totalLen,num[i],storeData,leastTimes); } changeStoreData(storeData,totalLen,false); cout<<"TestData: "< 代码并没有穷尽所有的测试样例,所以不一定就是完全正确的,如果有不通过的测试样例,欢迎大家评论和批评指正~



