public class Solution { public int MoreThanHalfNum_Solution(int [] array) { //定义一个计数器count,存放众数的变量 card int card = 0; int count = 0; //找这个数字,一样就 计数加1,不一样 减1,如果减到0,则将当前数赋给card,并计数为1 for(int x : array){ if(count == 0){ card = x; count = 1; } if(card == x){ count++; } else{ count--; } } //判断找出的数card是否超过数组的一半 int num = 0; for(int i = 0;i < array.length;i++){ if(card == array[i]){ num++; } } return (num > array.length / 2) ? card : 0; } }