解题思路:桶排序+使用LinkedHashMap来保持输出顺序;
又或者,读取输入时使用数组保存候选人名字的顺序
import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int candidates = sc.nextInt(); Map<String, Integer> votes = new LinkedHashMap<>(); for (int i = 0; i < candidates; i++) { votes.put(sc.next(), 0); } int invalid = 0; int tickets = sc.nextInt(); for (int i = 0; i < tickets; i++) { String ticket = sc.next(); if (votes.containsKey(ticket)) { votes.put(ticket, votes.get(ticket).intValue() + 1); } else { invalid++; } } for (Map.Entry<String, Integer> entry: votes.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue().intValue()); } System.out.println("Invalid : " + invalid); } } }