[设计思想]
因为水王是整个论坛中发帖和回帖数加起来最多的的人,且超过总帖数的一半以上。(这里将发帖数和回帖数记在一起)使用"两两相消"的方法。将帖子的作者id纳入数组,将数组中的一个数记作疑似水王者,并记发帖数t=0。遍历数组,若数组中的数和疑似水王者id相同,使发帖数t加一。如与疑似水王者id不同,使发帖数t减一。当t=0时,将数组中当前与水王疑似者比较的数作为新的疑似水王者。循环结束,当前水王怀疑者就是水王。
[代码实现]
import java.util.Scanner; public class KingOfWater { public static void main(String args[]){ int length; Scanner sc = new Scanner(System.in); System.out.println("请输入总帖数:"); length = sc.nextInt(); String Poster[] = new String[length]; System.out.println("请输入每个帖子的发帖者:"); for(int i=0;i<length;i++) { Poster[i] = sc.next(); } String suspect=Poster[0]; int t=0; for(int i=0;i<length;i++) { if(suspect.equals(Poster[i])) { t+=1; } else { t-=1; } if(t==0) { suspect = Poster[i]; t=1; } } System.out.println("事情的真相只有一个,TheKingOfWater是:"); System.out.println(suspect); } }
[实现截图]