用了集合,早知道用数组了
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int in = scanner.nextInt(); List<String> iList = new ArrayList<>(); for (int j = 0; j < in; j++) { iList.add(scanner.next()); } int rn = scanner.nextInt(); Set<Integer> rSet = new TreeSet<>(); for (int i = 0; i < rn; i++) { // 去重 rSet.add(scanner.nextInt()); } LinkedHashMap<String, List<Map<Integer, String>>> linkedHashMap = new LinkedHashMap<>(); Map<String, Integer> countMap = new LinkedHashMap<>(); int total = 0; Iterator<Integer> iterator = rSet.iterator(); // 遍历R while (iterator.hasNext()){ Integer r = iterator.next(); int count = 0; List<Map<Integer, String>> mapList = new ArrayList<>(); // 遍历I for (int i = 0; i < iList.size(); i++) { if (iList.get(i).contains(r + "")) { HashMap<Integer, String> map = new HashMap<>(1); // 添加索引以及对应的数据 map.put(i,iList.get(i)); mapList.add(map); count++; total += 2; } } if (!mapList.isEmpty()){ linkedHashMap.put(r + "",mapList); } // 数字对应在I的出现次数 if (count > 0){ countMap.put(r + "",count); } } // R的数量*2相当于有一个是R,有一个是R在I中的次数 + 所有下标加具体数据的数量 total = countMap.entrySet().size() * 2 + total; StringBuilder stringBuilder = new StringBuilder(); // 遍历统计次数的map for (Map.Entry<String, Integer> entry : countMap.entrySet()) { String rStr = entry.getKey(); stringBuilder.append(rStr + " " + entry.getValue() + " "); List<Map<Integer, String>> mapList = linkedHashMap.get(rStr); for (Map<Integer, String> map : mapList) { Map.Entry<Integer, String> next = map.entrySet().iterator().next(); stringBuilder.append(next.getKey() + " " + next.getValue() + " "); } } // 注意删除末尾的多余空格 System.out.println(total + " " + stringBuilder.deleteCharAt(stringBuilder.length() - 1)); } }