题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
来源:https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&tPage=2&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int count = 0;
int res = 0;
int len = array.length;
for(int i = 0;i<len;i++){
//初始化 or 重复数字被抵消,重新选出大哥
if(count==0){
res = array[i];
}
//如果重复,计数器加1,否则计数器-1
count += res==array[i]?1:-1;
}
//验证:
count = 0;
for (int i = 0; i < len; i++) {
if (res == array[i]) {
count++;
}
}
return count>len/2?res:0;
}
}