题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
import java.util.Map;
import java.util.HashMap;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int a = array.length / 2;
int res = 1;
Map<String,Integer> hp = new HashMap<>();
for(int i=0;i<array.length;i++){
String str = String.valueOf(array[i]);
if(hp.containsKey(str)){
int temp = hp.get(str);
temp++;
hp.put(str,temp);
}else{
hp.put(str,1);
}
//判断次数是否大于数组长度一半
if(hp.get(str) > a){
res = array[i];
}
}
return res;
}
}