题解 | #分组统计#这题的输出是真麻烦

分组统计

https://www.nowcoder.com/practice/5cb47b86911c4aa48722e531a51ec823

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        while (m-- > 0) {
            int n = sc.nextInt();
            int[] numbers = new int[n];
            for (int i = 0; i < n; i++) numbers[i] = sc.nextInt();
            Map<Integer, Map<Integer, Integer>> groupCounts = new HashMap<>();
            Set<Integer> allNumbers = new TreeSet<>();
            for (int i = 0; i < n; i++) {
                int number = numbers[i];
                int group = sc.nextInt();
                allNumbers.add(number);
                groupCounts.putIfAbsent(group, new HashMap<>());
                Map<Integer, Integer> countMap = groupCounts.get(group);
                countMap.put(number, countMap.getOrDefault(number, 0) + 1);
            }
            StringBuilder output = new StringBuilder();
            for (int group : groupCounts.keySet()) {
                Map<Integer, Integer> countMap = groupCounts.get(group);
                output.append(group).append("={");
                int[] all_numbers = allNumbers.stream().mapToInt(Integer::intValue).toArray();
                for (int i = 0; i < all_numbers.length; i++) {
                    int number = all_numbers[i];
                    int count = countMap.getOrDefault(number, 0);
                    output.append(number).append("=").append(count);
                    if (i < all_numbers.length - 1) output.append(",");
                }
                output.append("}\n");
            }
            System.out.print(output);
        }
    }
}

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
_mos_:我以为手抄报简历就已经很顶了,没想到还有表格简历
点赞 评论 收藏
分享
八股刚起步,看了javaguide,小林coding,还有面渣,感觉面渣是体验最好的,请问只看面渣够用吗,有不完善的需要补吗?
码农索隆:先背最基础的知识,然后理解情景题,现在面试大多数喜欢问情景题,更考验面试者的基础和临场发挥情况
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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