题解 | #数据分类处理#

数据分类处理

https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<String> strList = new ArrayList<>();
        while (in.hasNextLine()) {
            String str = in.nextLine();
            strList.add(str);
            if (strList.size() == 2) {
                String rStr = strList.get(0);
                String iStr = strList.get(1);
                // 处理R列中的数字
                String[] rStrs = rStr.split(" ");
                String[] iStrs = iStr.split(" ");
                Set<String> iStrSet = new HashSet<>();
                // 去掉第一个数字
                for (int i = 1; i < iStrs.length; i++) {
                    iStrSet.add(iStrs[i]);
                }
                Map<String, Map<Integer, String>> map = new HashMap<>();
                for (String s : iStrSet) {
                    for (int i = 1; i < rStrs.length; i++) {
                        String indexStr = rStrs[i];
                        if (indexStr.contains(s)) {
                            Map<Integer, String> indexMap = map.get(s);
                            if (indexMap == null) {
                                indexMap = new HashMap<>();
                                map.put(s, indexMap);
                            }
                            // 数字实际的位置不包含首个的个数
                            indexMap.put(i - 1, indexStr);
                        }
                    }
                }
                List<String> keys = new ArrayList<>(map.keySet());
                Collections.sort(keys, Comparator.comparingInt(Integer::parseInt));
                List<String> outputList = new ArrayList<>();
                for (String key : keys) {
                    Map<Integer, String> indexMap = map.get(key);
                    outputList.add(key);
                    outputList.add(String.valueOf(indexMap.size()));
                    List<Integer> indexKeys = new ArrayList<>(indexMap.keySet());
                    Collections.sort(indexKeys);
                    for (Integer indexKey : indexKeys) {
                        String indexStr = indexMap.get(indexKey);
                        outputList.add(String.valueOf(indexKey));
                        outputList.add(indexStr);
                    }
                }
                StringBuilder sb = new StringBuilder();
                sb.append(outputList.size()).append(" ");
                outputList.forEach(e -> sb.append(e).append(" "));
                sb.deleteCharAt(sb.length() - 1);
                System.out.println(sb);
                strList.clear();
            }
        }
    }
}

全部评论

相关推荐

MingoTree:看不出你你的技术栈,想找什么工作,然后课设项目别写上去了,自我评价删了,前后端你想好你要干啥,这种简历投上去秒挂的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务