您的位置:首页 > 其它

2.3 寻找发帖水王

2014-12-03 21:25 302 查看
问题描述:

Tango是微软亚洲研究院的一个试验项目。研究院的员工和实习生们都很喜欢在Tango上面交流灌水。传说,Tango有一大“水王”,他不但喜欢发贴,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子总数的一半。如果你有一个当前论坛上所有帖子(包括回帖)的列表,其中帖子作者的ID也在表中,你能快速找出这个传说中的Tango水王吗?

思路,遍历一遍,只要遇到两个不一样的(不管包括不包括水王的帖)就一起删去,最后剩下的,肯定水王的帖子肯定还是大于一半的。

总结下大致思想就是:假设每个ID都有可能是水王,那么在遍历时这个水王就要遇到一种挑战,可能自己的帖子数是会增加的,也可能是遇到挑战的,帖子数要减少的。这样遍历下来,只有水王的帖子增加的减去遇到挑战的帖子数会是大于0的。其他任何帖子假设为水王时都是禁不起挑战的。

代码:
int ntime = 0;
string result;
for(int i = 0; i < n; ++i) {
if(ntime == 0) {
result = array[i];
ntime = 1;
}else {
if(result == array[i]) ntime++;
esle ntime--;
}
return result;
}


扩展问题:

随着Tango的发展,管理员发现,“超级水王”没有了。统计结果表明,有3个发帖很多的ID,他们的发帖数目都超过了帖子总数目N的1/4。你能从发帖ID列表中快速找出他们的ID吗?

同样的道理!
代码:
int ntimes[3] = {0};
string result[3];
for(int i = 0; i < n; ++i) {
if (ntimes[0] == 0) {
result[0] = array[i];
ntimes[0] = 1;
} else if (ntimes[1] == 0) {
result[1] = array[i];
ntimes[1] = 1;
} else if (ntimes[2] == 0) {
result[3] = array[i];
ntimes[2] = 1;
}else if (result[0] == array[i]) {
ntimes[0]++;
}else if (result[1] == array[i]) {
ntimes[1]++;
}else if (result[2] == array[i]) {
ntimes2++;
}else {
ntimes[0]--;
ntimes[1]--;
ntimes[2]--;
}
return ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: