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

分组统计

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

全部评论

相关推荐

joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务