查找水王

队友:高雪彤 


 

1、编程思路:

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

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

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

为更小的问题),从而得到问题的答案。

2、代码实现

public class WaterGod {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] a = { 1, 2, 2, 2, 1, 1, 1, 1 };
        int result = 0;
        int times = 0;

        for (int i = 0; i < a.length; i++) {
            if (times == 0) {
                result = a[i];
                times = 1;
            } else {
                if (result == a[i]) {
                    ++times;
                } else {
                    --times;
                }
            }
        }

        System.out.println(result);
    }
}

3、总结

     思路固然重要,几次的课堂测试均是思路无法达到。

      

posted @ 2017-04-18 19:45  树深时见鹿``  阅读(129)  评论(0编辑  收藏  举报