面试题39(剑指offer)--数组中出现次数超过一半的数字

2019-08-19  本文已影响0人  Tiramisu_b630

题目:

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

思路:

代码:

    private static int numOfDigital(int[] array){
        if (array==null||array.length==0){
            return -1;
        }
        int len=array.length;
        int temp=array[0];
        int count=1;
        for (int i = 1; i <len ; i++) {
            if (array[i]==temp){//下一个和上一个相同则次数加1
                count++;
            }else if (count==0){//次数为0时,设置新的数字并置次数为1
                temp=array[i];
                count++;
            }else {
                count--;//次数不为0且与前一个不相同,则次数减1
            }
        }
        if (!checkValid(array,temp)){
            return 0;
        }
        return temp;
    }
    private static boolean checkValid(int[] array, int temp) {//检查是不是没有数字超过数组的一半
        int count=0;
        for (int i : array) {
            if (i==temp) {
                count++;
            }
        }
        if (count>array.length/2){
            return true;
        }
        return false;
    }
上一篇 下一篇

猜你喜欢

热点阅读