题解 | #数据分类处理#
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //读取I值放入数组中,以保持原顺序 int n1 = sc.nextInt(); String[] I = new String[n1]; for (int i = 0; i < n1; i++) { I[i] = String.valueOf(sc.nextInt()); } //读取R值存入TreeSet中,以便去重和排序 int n2 = sc.nextInt(); TreeSet<Integer> set = new TreeSet<>(); for (int j = 0; j < n2; j++) { set.add(sc.nextInt()); } //获得各个R<i>所对应的满足条件的I的个数,存入LinkedHashMap中,以保持TreeSet中R<i>的排序 LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>(); for (int r : set) { for (int i = 0; i < n1; i++) { if ((I[i]).contains(r + "")) { if (!map.containsKey(r)) { map.put(r, 1); } else { map.put(r, map.get(r) + 1); } } } } //按顺序要求将数据依次存入list中 List<Integer> list = new ArrayList<>(); for (int key : map.keySet()) { //存入R<i> list.add(key); //存入R<i>满足条件的I的个数 list.add(map.get(key)); for (int i = 0; i < n1; i++) { if ((I[i]).contains(key + "")) { //存入I的位置索引和I值 list.add(i); list.add(Integer.parseInt(I[i])); } } } System.out.print(list.size()); for (int k : list) { System.out.print(" " + k); } } }