题目:
HJ94 记票统计
题解:
利用哈希表,投票是按姓名从哈希表中取出对应的票数,如果不在哈希表内证明为无效。
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);int n = Integer.valueOf(in.nextLine());String nameString = in.nextLine();int number = Integer.valueOf(in.nextLine());String string = in.nextLine();Map<String, Integer> nameMap = new HashMap<>();String[] names = nameString.split(" ");for (String name : names) {nameMap.put(name, 0);}String[] arr = string.split(" ");for (String s : arr) {Integer count = nameMap.get(s);if (count == null) {nameMap.put("Invalid", nameMap.getOrDefault("Invalid", 0) + 1);} else {nameMap.put(s, count+1);}}for (String name : names) {System.out.printf("%s : %s\n", name, nameMap.get(name));}System.out.printf("%s : %s\n", "Invalid", nameMap.getOrDefault("Invalid", 0));}
}
时间复杂度:O(n)