剑指offer---数组中出现次数超过一半的的数字(Java)

题目描述

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

解析思路

在这里插入图片描述

实现代码

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        int length = array.length;
        if(array == null || length == 0){
            return 0;
        }
        int tmp = array[0];
        int counts= 1;
        for(int i = 1;i<length;i++){
            if(counts == 0){
                tmp = array[i];
                counts =1;
            }else{
                if(array[i] == tmp){
                    counts++;
                }else{
                    counts--;
                }
            }
        }
        counts=0;
        for(int i = 0;i<length;i++){
            if(tmp == array[i]){
            counts++;
            }
        }
        if(counts*2>length){
            return tmp;
        }
        return 0;
    }
}

运行截图

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章