给一个长度为n的数组,数组内有一个数字出现的次数超过了数组长度的一半,请找出这个数字
eg:[1,2,3,2,2,2,5,4,2]
2在数组中出现了5次,超过数组长度一半,输出2
eg:[1],输出1
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length==1){
return array[0];
}
int mid=array.length/2;
int max=0;
HashMap<Integer,Integer> hashMap=new HashMap<>();
for(int i=0;i<array.length;i++){
if(hashMap.get(array[i])!=null){
int tmp=hashMap.get(array[i]);
if(tmp+1>mid){
max=array[i];
}
hashMap.put(array[i],tmp+1);
}else{
hashMap.put(array[i],1);
}
}
return max;
}