题解 | #简单错误记录#
简单错误记录
http://www.nowcoder.com/practice/2baa6aba39214d6ea91a2e03dff3fbeb
思路:先用LinkedHashMap保存输入的数据,分2种情况,第一种是总的记录条数<=8,直接输出即可;第二种是记录数>8,移除掉前n(n = map.size - 8)个元素,输出剩下的最后8个元素。如果需要排序,用
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {} 参考代码:import java.util.*; public class ErrFileCnt01 { public static void main(String[] args) { Map<String, Integer> cntMap = new LinkedHashMap<>(); Scanner sc = new Scanner(System.in); String path; String file; String key; while (sc.hasNext()) { path = sc.next(); int lineMum = sc.nextInt(); int index = path.lastIndexOf('\\'); String tmpFile = index > 0 ? path.substring(index + 1) : path; file = tmpFile.length() > 16 ? tmpFile.substring(tmpFile.length() - 16) : tmpFile; key = file + " " + lineMum; if (!cntMap.containsKey(key)) { cntMap.put(key, 1); } else { cntMap.put(key, cntMap.get(key) + 1); } } sc.close(); List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(cntMap.entrySet()); int size = list.size();//列表元素个数,等于总数减去重复的 size = total - duplicate if (size <= 8) { for (Map.Entry<String, Integer> entry : list) { String[] strs = entry.getKey().split(" "); String file1 = strs[0]; String line1 = strs[1]; System.out.println(file1 + " " + line1 + " " + entry.getValue()); } } else { int removeCnt = size - 8; //需要移除的前N个元素,保留需要打印的最后8个 for (int a = 0; a < removeCnt;) { list.remove(0); a++; } for (Map.Entry<String, Integer> entry : list) { String[] strs = entry.getKey().split(" "); String file1 = strs[0]; String line1 = strs[1]; System.out.println(file1 + " " + line1 + " " + entry.getValue()); } } } }