找水王
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("\n第" + 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("\n水王id为:" + shuiwang);
36 br.close();
37 }
38
39 }
设计思想:本题的设计是采用我们都玩过的游戏“消消乐”的算法,由于”水王“的帖子超过了所有帖子的一半,相邻的两个ID可以采用抵消的方法:不同消去,相同合并,最后剩下的一定是水王的帖子。