题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
int n = sc.nextInt();
sc.nextLine();//消耗 nextInt的换行符 next不会读取这个换行符
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int i = 0; i < n; i++) {
String str = sc.nextLine();
String[] split = str.split(" ");
int idx = Integer.parseInt(split[0]);
int val = Integer.parseInt(split[1]);
map.put(idx, map.getOrDefault(idx,
0) + val); // 使用getOrDefault处理键不存在的情况
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
} finally {
sc.close();
}
}
}

