题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 这种n没啥用 顶多在下面的循环里再加个判断 食之无味弃之可惜 int n = in.nextInt(); Map<Integer, Integer> map = new TreeMap<>(); while (in.hasNextInt()) { int k = in.nextInt(); int v = in.nextInt(); map.put(k, map.getOrDefault(k, 0) + v); } for(Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } }
更新时间: 2023-03-15 9:43
摸鱼中,更优雅的写法
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Map<Integer, Integer> treeMap = new TreeMap<>(); while (n-- > 0) { final int key = in.nextInt(); final int value = in.nextInt(); treeMap.compute(key, (k, v) -> v == null ? value : v + value); } treeMap.forEach((k, v) -> System.out.printf("%s %s\n", k, v)); } }#华为笔试#