题解 | #记票统计#
记票统计
https://www.nowcoder.com/practice/3350d379a5d44054b219de7af6708894
思路:使用一个map集合存储候选人的姓名与投票数,程序要求按输入顺序输出结果,应该用LinkedHashMap,代码如下:
import java.util.*; import java.io.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) throws IOException { // Scanner in = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; // 注意 hasNext 和 hasNextLine 的区别 while ((str = br.readLine()) != null) { // 注意 while 处理多个 case int n = Integer.parseInt(str); String[] s = br.readLine().split(" "); Map<String, Integer> candidate = new LinkedHashMap<>(); for (int i = 0; i < n; i++) { candidate.put(s[i], 0); } int m = Integer.parseInt(br.readLine()); s = br.readLine().split(" "); int Invalid = 0; for (int i = 0; i < m; i++) { if (candidate.containsKey(s[i])) { int num = candidate.get(s[i]) + 1; candidate.put(s[i], num); }else Invalid++; } for (String key : candidate.keySet()) { int value = candidate.get(key); System.out.println(key + " : " + value); } System.out.println("Invalid" + " : " + Invalid); } } }