public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
//注意空间复杂度是O(1)
//用Map来保存每个数字出现的个数
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0;i < array.length;i++){
int n = array[i];
Integer value = map.get(n);
if(value == null){
map.put(n,1);
} else {
map.put(n,value + 1);
}
}
for(int key : map.keySet()){
int value = map.get(key);
if(value > array.length / 2){
return key;
}
}
return -1;
}
}