import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取候选人数量
int n = scanner.nextInt();
scanner.nextLine(); // 跳过换行符
// 读取候选人名字并初始化数据结构
String[] candidateNames = scanner.nextLine().split("\\s+");
List<String> candidates = Arrays.asList(candidateNames);
Set<String> candidateSet = new HashSet<>(candidates);
Map<String, Integer> votes = new HashMap<>();
for (String name : candidates) {
votes.put(name, 0);
}
// 读取投票数量
int m = scanner.nextInt();
scanner.nextLine(); // 跳过换行符
// 读取投票内容并统计
String[] votesArray = scanner.nextLine().split("\\s+");
int invalid = 0;
for (String vote : votesArray) {
if (candidateSet.contains(vote)) {
votes.put(vote, votes.get(vote) + 1);
} else {
invalid++;
}
}
// 输出结果
for (String name : candidates) {
System.out.println(name + " : " + votes.get(name));
}
System.out.println("Invalid : " + invalid);
}
}
https://www.nowcoder.com/discuss/727521113110073344
思路:
- 输入处理:使用Scanner读取输入数据。注意处理换行符以避免读取错误。
- 数据结构初始化:使用列表保存候选人名字以保持顺序,集合用于快速查询,哈希表记录票数。
- 统计票数:遍历每张选票,有效票更新对应候选人的票数,无效票计数。
- 输出结果:按输入顺序遍历候选人列表,输出每位候选人的票数,最后输出无效票数量。



京公网安备 11010502036488号