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

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

作者: Tiramisu_b630 | 来源:发表于2019-08-19 18:36 被阅读0次

题目:

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

思路:

  • 有一个数字超过数组的一半,就是说有一个数字出现的次数比其他数字次数的和还要大,可以考虑遍历数组保存两个值数字以及其出现的次数,如果下一个数字和前一个数字不同且前一个数字不为零,则次数减一,如果次数为0则保存下一个数字,并及次数为1。
  • 由于可能会出现没有数字超过数组的一半,所以加入checkValid函数用来检验。

代码:

    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;
    }

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/icbesctx.html