数组中出现次数超过一半的数字
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
//遍历数组,值标记位key
//新建一个map,map包含这个key,那么对应的value+1,map不包含这个key,那么对应的value设置为1
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0; i<array.length; i++){
Integer key = array[i];
if(!map.containsKey(key)){
map.put(key,1);
}else{
int tmp_v = map.get(key);
map.put(key,tmp_v+1);
}
}
float half = array.length/2;
for(Integer k:map.keySet()){
if(map.get(k)>half){
return k;
}
}
return -1;
}
}

浙公网安备 33010602011771号