找水王

设计思想

水王帖子的数量大于总数的一半,所以水王的ID与其他ID互相抵消之后会剩下最后的水王。首先输入数组长度,定义数组,输入帖子列表;对数组操作,设置shui和num=0。若num=0,shui等于当前的数组中的数字;shui=当前数组中的数字,num++;否则就消掉一个,num--。在最后的时候判断一下水王ID是否超过了总数的一半,若没超过,他只是发帖最多人,不是水王!

代码实现

 1 package shuiwang;
 2 
 3 import java.util.Scanner;
 4 
 5 public class seclect {
 6     
 7     @SuppressWarnings("resource")
 8     public static void main(String[] args) {
 9         System.out.println("请输入ID列表长度");
10         Scanner s = new Scanner(System.in);
11         int length = s.nextInt();//数组长度
12         int [] a = new int [length];
13         
14         //输入数组
15         System.out.println("请输入数组:");
16         for(int i = 0;i < length;i++)
17             a[i] = s.nextInt();
18         
19         //找水王
20         int shui = 0, num = 0;
21         for(int i = 0;i < length;i++)
22         {
23             if(num == 0)
24             {
25                 shui = a[i];
26                 num ++;
27             }
28             else if(shui == a[i])
29             {
30                 num ++;
31             }
32             else
33             {
34                 num --;
35             }    
36         }
37         
38         //判断是否是水王
39         num = 0;
40         for(int i = 0;i < length;i++)
41         {
42             if(a[i] == shui)
43             {
44                 num ++;
45             }
46         }
47         if(num >= length / 2)
48             System.out.println("水王ID:" + shui);
49         else
50             System.out.println("无水王!");
51     }
52 
53 }

实现截图

     

个人总结

思考很重要,在有一个思路的时候,不妨写下来;然后寻找更加优化的算法,在最后的算法时,要测试各种例子,各种偏的例子,甚至可以测试不符合题目要求或者没有答案的来完善代码!

原文地址:https://www.cnblogs.com/fylove/p/6729310.html