码迷,mamicode.com
首页 > 编程语言 > 详细

数组中出现次数超过一半的数字

时间:2018-07-01 11:50:53      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:ring   次数   span   eth   个数   IV   color   数字   stat   

题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。

public class MoreThanHalf{
    public int getMoreThanHalf(int[] array){
        if(array==null || array.length==0) return -1;
        int result = array[0];
        int count = 0;
        for(int i=0;i<array.length;i++){
            if(count ==0){
                result = array[i];
                count = 1;
            }else if(result == array[i]){
                count++;
            }else{
                count--;
            }
        }
        count = 0;
        for(int i=0;i<array.length;i++){
            if(result == array[i]){
                count++;
            }
        }
        if(count > (array.length/2)){
            return result;
        }
        return -1;
    }
    public static void main(String[] args){
        int[] array = {1,2,3,2,2,2,5,4,2};
        MoreThanHalf m = new MoreThanHalf();
        int result = m.getMoreThanHalf(array);
        System.out.println(result);
    }
}

 

数组中出现次数超过一半的数字

标签:ring   次数   span   eth   个数   IV   color   数字   stat   

原文地址:https://www.cnblogs.com/yingpu/p/9249434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!