描述
给一个长度为 n 的数组,数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
解题思路:
可以假设第一个数为出现最多数,设置出现次数为1.依次与之后每个数比较,如果相等,则次数+1,不相等次数-1,只到减为0,赋值新的值
public int MoreThanHalfNum_Solution(int [] array) {
int temp=array[0];
int count =1;
for(int i=1;i<array.length;i++){
if(array[i]==temp){
count++;
}else{
count--;
if(count==0){
count=1;
temp=array[i];
}
}
}
return temp;
}