查找水王 4.17

队友:刘雨鑫


 

编程思路:  

  老师在上课中提到过,利用对子问题来解决水王问题。

  水王的特点为:(1)每贴必回(2)水王的发贴数超过总贴数的一半;

  如果每次删除两个不同的ID,那么剩下的ID列表中,“水王”ID出现的次数仍然超过总数的一半。看到这一点后,就可以通过不断重复这个过程,把ID列表中的ID总数降低(转化为更小的问题),从而得到问题的答案。  

 1 package tt20170227;
 2 
 3 public class WaterGod {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7 
 8         int[] a = { 1, 2, 2, 2, 1, 1, 1, 1 };
 9         int result = 0;
10         int times = 0;
11 
12         for (int i = 0; i < a.length; i++) {
13             if (times == 0) {
14                 result = a[i];
15                 times = 1;
16             } else {
17                 if (result == a[i]) {
18                     ++times;
19                 } else {
20                     --times;
21                 }
22             }
23         }
24 
25         System.out.println(result);
26     }
27 }

 

posted on 2017-04-18 19:39  鲨鱼姑娘  阅读(179)  评论(0编辑  收藏  举报