题解 | #记票统计#

记票统计

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);
        }
    }
}



全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-04 18:06
点赞 评论 收藏
分享
Gaynes:查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务