找水王

一、要求

  三人行设计了一个灌水论坛。信息学院的学生都喜欢在上面交流灌水,传说在论坛上有一个“水王”,他不但喜欢发帖,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子数目的一半。 如果你有一张当前论坛的帖子(包括回帖)列表,其中帖子的作者的ID也在其中,你能快速的找到这个传说中的水王吗?

二、分析

  题目中最重要的一个条件是:“水王”发帖数目超过了帖子数目的一半

  跟据此条件可以设计出一个算法:读取前两个帖子发帖人id,比较,如果不同,全部丢弃,接着读取之后两个id;如果相同,丢弃一个,读取之后一个id;以此类推,直到读取并比较完所有id,剩下的最后一个id就是“水王”的id。

  但是,这种方法有点小问题,某些情况就不适用,比如以下情况可以看出AAA为“水王”id,但根据上述算法却得出结果为654(我设置了一个中间变量,用于记录两次读取的值相同时,值为多少)。

 1 165
 2 AAA
 3 AAA
 4 965
 5 AAA
 6 AAA
 7 AAA
 8 654
 9 654
10 654
11 AAA

三、txt文件

list.txt

 1 165
 2 99999
 3 155
 4 99999
 5 155
 6 12
 7 99999
 8 51
 9 155
10 99999
11 89
12 99999
13 99999
14 98
15 99999
16 99999
17 165
18 99999
19 99999

四、源代码

 1 import java.io.BufferedReader;
 2 import java.io.FileReader;
 3 import java.io.IOException;
 4 
 5 
 6 public class FindIdlePeople {
 7     public static void main(String[] args) throws IOException {
 8         find();
 9     }
10     
11     public static void find() throws IOException {
12         BufferedReader br = new BufferedReader(new FileReader("list.txt"));
13         String s,s1 = null,s2 = null,shuiwang = null;
14         int i=1;
15         while((s = br.readLine()) != null) {
16             s1 = s;
17             if(s2 == null) {
18                 s2 = br.readLine();
19             }
20             System.out.println("
第" + i++ + "次比较");
21             System.out.println("s1:" + s1);
22             System.out.println("s2:" + s2);
23             if(s2 != null) {      //判断是否读到末尾即s2是否读了一个空行
24                 if(s1.compareTo(s2) != 0)   //两个值不同,s2重置,因为s1每次都重置,所以不用管s1
25                     s2 = null;
26                 else                        //两个值相同,s2不重置,将相同的值当作水王记录下来
27                     shuiwang = s2;
28             }else {
29                 shuiwang = s1;
30             }
31             System.out.println("记录id:" + shuiwang);
32         }
33         if(shuiwang == null)
34             shuiwang = s2;
35         System.out.println("
水王id为:" + shuiwang);
36         br.close();
37     }
38     
39 }
原文地址:https://www.cnblogs.com/dream0-0/p/11067280.html