题解 | #数据分类处理# Java内置数据结构解法
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
import java.util.Arrays; import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.nextLine(); String[] L = a.split(" "); String[] L1 = Arrays.copyOfRange(L,1,L.length); String b = in.nextLine(); String[] R = b.split(" "); String[] R1 = Arrays.copyOfRange(R,1,R.length); //TreeMap的key是R<i>, value是<index,正整数> TreeMap<Integer,LinkedHashMap<Integer,String>> tree = new TreeMap<>(); for(int i = 0; i < R1.length ; i++){ LinkedHashMap<Integer,String> empty = new LinkedHashMap<>(); tree.put(Integer.parseInt(R1[i]) ,empty); } for(int key_t : tree.keySet()){ for (int m = 0; m < L1.length;m++){ if (L1[m].contains(Integer.toString(key_t))){ //LinkedHashMap满足遍历时按插入顺序,index自带顺序且唯一。 tree.get(key_t).put(m,L1[m]); } } } String ans = ""; int all = 0; for(int key_t : tree.keySet()){ if (tree.get(key_t).size() == 0){ continue; }else{ all += 2; ans = ans + key_t + " " + tree.get(key_t).size() +" "; for(int key_L : tree.get(key_t).keySet()){ all += 2; ans = ans + key_L + " "+ tree.get(key_t).get(key_L)+ " "; } } } ans = all + " " + ans; System.out.println(ans); } }
直接结合两个数据结构,在插入的时候就保证顺序,最后遍历内容提供输出。TreeMap提供自带的key值顺序而且key唯一满足R去重。LinkedHashMap提供键值对按插入顺序遍历。感觉就是拿个空间换代码好看的解法。