投票法

由于众数的数量超过数组长度的一半,所以可以采用投票的方式,当候选者的票数为0后需要更换候选者,否则当遇到候选者时票数增加,当遇到其他数时票数减一,最后获胜的一定是这个超过数组长度一半的众数

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        //投票法
        int cond = -1;
        int cnt = 0;
        int len = array.length;
        if(len==0) return 0;
        for(int i = 0;i < len;i++){
            if(cnt==0){
                cond = array[i];
                cnt++;
            }else{
                if(cond==array[i]) cnt++;
                else cnt--;
            }
        }
        return cond;
    }
}