找水王
三人行设计了一个灌水论坛。信息学院的学生都喜欢在上面交流灌水,传说在论坛上有一个“水王”,他不但喜欢发帖,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子数目的一半。
如果你有一张当前论坛的帖子(包括回帖)列表,其中帖子的作者的ID也在其中,你能快速的找到这个传说中的水王吗?
package main;
import java.util.*;
public class Item {
public static void main(String[] args) {
// TODO Auto-generated method stub
Find_function function = new Find_function();
Scanner sca=new Scanner(System.in);
System.out.println("输入帖子数:");
int n=sca.nextInt();
String post[]=new String[n+1];
int i;
System.out.println("输入帖子ID:");
for(i=0;i<n+1;i++)
{
post[i]=sca.nextLine();
}
String shuiwang = function.find(post, n);
System.out.println("水王ID是 " + shuiwang);
}
}
class Find_function {
String find(String[] post,int n)
{
int i,j = 0;
String shuiwang = post[0];//令第一个ID为水王
for(i=0;i<n;i++)
{
if(!shuiwang.equals(post[i]))
{
j=j-1;
if(j<=0) //如果j=0时,之前的ID一定有一半以上不是水王,所以消去的至多有一半水王
{
shuiwang=post[i+1]; //在剩下的ID中继续寻找
j=1; //重新定义水王ID出现次数
i++;
}
}
else
{
shuiwang=post[i];
j=j+1;//水王帖子数
}
}
return shuiwang;
}
}

浙公网安备 33010602011771号