小R从班级中抽取了一些同学,每位同学都会给出一个数字。已知在这些数字中,某个数字的出现次数超过了数字总数的一半。现在需要你帮助小R找到这个数字。 代码 import java.util.HashMap;
public class Main { public static int solution(int[] array) { // 使用哈希表记录每个数字出现的次数 HashMap<Integer, Integer> countMap = new HashMap<>();
// 遍历数组,统计每个数字的出现次数
for (int num : array) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
// 遍历哈希表,找到出现次数超过一半的数字
int halfLength = array.length / 2;
for (int num : countMap.keySet()) {
if (countMap.get(num) > halfLength) {
return num;
}
}
// 如果没有找到符合条件的数字,返回0(题目保证一定存在这样的数字)
return 0;
}
public static void main(String[] args) {
// Add your test cases here
System.out.println(solution(new int[]{1, 3, 8, 2, 3, 1, 3, 3, 3}) == 3);
}
}