题解 | #数据分类处理#
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
问题梳理
- 找出 I 中包含 R[i] 的所有元素;
- 存在, 则输出 R[i], I 中满足条件的元素个数, 元素索引, 元素值;
- 对 R[i] 进行排序(从小到大), 并去重;
- 需要序列起始位置 统计并输出后序元素个数;
思路
- 借助 TreeSet 对 R[i] 进行去重和排序;
- I 放入数组就行;
- 遍历 I 并与 R[i] 进行比较, 封装 Found, 用于记录比较结果 {R[i], iIndexs};
- 将比较结果放入 foundList, 以便保持顺序和统计数量;
- 将 foundList 按指定格式进行输出;
代码实现
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { // 封装查找结果 public static class Found { public String r; public ArrayList<Integer> iIndexs; public Found(String r, ArrayList<Integer> iIndexs) { this.r = r; this.iIndexs = iIndexs; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); String iLine = in.nextLine(); String rLine = in.nextLine(); String[] I = iLine.substring(iLine.indexOf(" ") + 1).split(" "); String[] R = rLine.substring(rLine.indexOf(" ") + 1).split(" "); // R 排序并去重 TreeSet<Integer> RTree = new TreeSet(); for (int i = 0; i < R.length; i++) RTree.add(Integer.valueOf(R[i])); // 遍历寻找符合条件的 I, 存入 foundList Iterator RI = RTree.iterator(); ArrayList<Found> foundList = new ArrayList(); while (RI.hasNext()) { String rStr = String.valueOf(RI.next()); ArrayList<Integer> iIndexs = new ArrayList(); for (int j = 0; j < I.length; j++) { if (I[j].contains(rStr)) iIndexs.add(j); } if (iIndexs.size() > 0) foundList.add(new Found(rStr, iIndexs)); } // 寻找完成, 按指定格式输出 foundList LinkedList<String> outputItems = new LinkedList(); for (int k = 0; k < foundList.size(); k++) { Found found = foundList.get(k); outputItems.add(found.r); outputItems.add(String.valueOf(found.iIndexs.size())); for (Integer index : found.iIndexs) { outputItems.add(String.valueOf(index)); outputItems.add(I[index]); } } // 头部添加元素个数 outputItems.addFirst(String.valueOf(outputItems.size())); System.out.println(String.join(" ", outputItems)); } }