剑指offer题解汇总
https://blog.csdn.net/guliguliguliguli/article/details/126089434
本题链接
https://www.nowcoder.com/exam/oj/ta?difficulty=2&page=1&pageSize=50&search=&tpId=13&type=265
题目
思路 & 代码
用hashmap来存储数组中每一个数字出现的次数
-
先检查该数组中是否有以该值为键的键值对
-
有,在原有的基础上加1,表示该数字又出现了一次
-
没有,向map中添加以该值为键,1为值的键值对
-
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int[] array) {
int len = array.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i : array) {
if (map.containsKey(i)) {
map.put(i, map.get(i) + 1);
} else {
map.put(i, 1);
}
if (map.get(i) > len / 2) {
return i;
}
}
return -1;
}
}