题解 | #数组中出现次数超过一半的数字#利用map实现
数组中出现次数超过一半的数字
http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
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;
}
}