题解 | #记票统计#

记票统计

http://www.nowcoder.com/practice/3350d379a5d44054b219de7af6708894

题解

此题没什么难度,可以使用数组来统计投票结果,因为数组是有序的。

代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            // 1.输入初始化
            int n = sc.nextInt(); // 候选人数
            String[] name = new String[n]; // 候选人名字
            for (int i = 0; i < n; i++) {
                name[i] = sc.next();
            }

            int m = sc.nextInt(); // 投票人数
            String[] select = new String[m]; // 投票人投票的候选人
            for (int i = 0; i < m; i++) {
                select[i] = sc.next();
            }

            // 2.统计票数
            // 四个人的票数统计,此处下标为n的表示统计不合法的字符数
            int[] count = new int[n + 1];
            for (int i = 0; i < m; i++) {
                boolean flag = false; // 标记该投票是否合法
                for (int j = 0; j < n; j++) {
                    if (select[i].equals(name[j])) {
                        count[j]++;
                        flag = true; // 合法标记
                        break;
                    }
                }
                if (!flag) { // 如果不合法,将不合法+1
                    count[n]++;
                }
            }

            // 3.打印结果
            for (int i = 0; i < count.length; i++) {
                if (i == n) { // 输出不合法的字符
                    System.out.println("Invalid : " + count[i]);
                    break;
                }
                System.out.println(name[i] + " : " + count[i]);
            }

        }
    }
}
全部评论

相关推荐

神哥不得了:神哥来啦~1.建议不要包装,很容易问穿2.没日常也能找到暑期3.简历模板换一下,字体和版式看着好难受,而且最好压缩到一页,技术的倒数第2和3重复啦,项目建议换两个高质量的上去,如果时间够的话,八股就把高频top50的题目多巩固几遍,吃透,注意不要找假高频,这样绝对能找到暑期
点赞 评论 收藏
分享
评论
5
2
分享

创作者周榜

更多
牛客网
牛客企业服务