找水王

题目要求:

三人行设计了一个灌水论坛。信息学院的学生都喜欢在上面交流灌水,传说在论坛上有一个“水王”,他不但喜欢发帖,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子数目的一半。

如果你有一张当前论坛的帖子(包括回帖)列表,其中帖子的作者的ID也在其中,你能快速的找到这个传说中的水王吗?

package www;
public class water {
    public static int findbetter(int[] array)  
    {  
        int size = array.length;  
        int result = 0;// 需要查找的结果  
        int times = 0;// 出现的次数  
        for (int i = 0; i < size; i++)  
        {  
            // 如果次数等于0,重新指定结果  
            if (times == 0)  
            {  
                result = array[i];  
                times = 1;  
            }  
            else  
            {  
                if (result == array[i])  
                {  
                    ++times;  
                }  
                else  
                {  
                    --times;  
                }  
            }  
        }  
        return result;  
    }  
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int []list= {1,2,1,3,1,4,1,1,1,1,1,3};
        System.out.println("水王是:"+findbetter(list));
    }
}

运行截图:

思想:水王ID出现的次数一定是要大于一半的。因此水王的ID要么会有连续出来的情况,要么位于最后一个

原文地址:https://www.cnblogs.com/xcl666/p/11071341.html