哈希表

给定一个长度为 n 的整数数列 N,其中第 i 个数为 N_i(1 ≤ i ≤ n)。已知数列中某一个数出现的次数大于等于 ⌈n/2⌉(即向上取整的 n 的一半)。请找出这个数。

输入格式:
第一行包含一个整数 n,表示整数数列的长度。
第二行包含 n 个整数,即为该整数数列。

import java.util.Scanner;
import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(arr[i],map.getOrDefault(arr[i],0)+1);
}
int Max = 0;
int result = 0; // 用来记录值最大的那个键

// 直接遍历键值对
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > Max) {
Max = entry.getValue();
result = entry.getKey();
}
}

System.out.println(result);
}

}

posted @ 2026-05-29 22:00  鬼计i  阅读(4)  评论(0)    收藏  举报