import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 1. 读取总票数n
int n = scanner.nextInt();
// 2. 创建投票数组
int[] votes = new int[n];
for (int i = 0; i < n; i++) {
votes[i] = scanner.nextInt();
}
// 3. 用数组统计次数(编号范围1-1000)
int[] count = new int[1001];
for (int i = 0; i < n; i++) {
count[votes[i]]++;
}
// 4. 找出出现最多的次数
int maxCount = 0;
for (int i = 1; i <= 1000; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
}
}
// 5. 找出第一个出现次数等于最大次数的编号
int result = 0;
for (int i = 0; i < n; i++) {
if (count[votes[i]] == maxCount) {
result = votes[i];
break; // 找到第一个就退出
}
}
// 6. 输出结果
System.out.println(result);
scanner.close();
}
}
简单即美:能用 int[1001] 解决,就别用 HashMap<Integer, Integer>
明确目标:代码的每一步都直指问题核心,没有多余操作
利用已知条件:题目条件(编号范围)是解决问题的利器
可读性至上:代码清晰到不需要注释也能看懂
如果编号范围未知(比如1-10^9),还能这么用数组吗?
如果要求输出“所有票数最多的编号”,而不是“第一个”,该怎么改?
如果n很大(比如10^7),两次遍历会不会成为性能瓶颈?
