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> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int x = in.nextInt();
int y = in.nextInt();
map.put(x, map.getOrDefault(x, 0) + y);
}
List<Integer> sortedKeys = new ArrayList<>(map.keySet());
Collections.sort(sortedKeys);
for (int key : sortedKeys) {
System.out.println(key + " " + map.get(key));
}
}
}
https://www.nowcoder.com/discuss/727521113110073344
思路:
- 读取输入:使用Scanner读取输入的记录数n。
- 哈希表合并:使用HashMap存储索引和对应的数值总和。map.getOrDefault(x, 0)方法用于获取当前索引的值,若不存在则返回0,然后加上当前数值y。
- 排序输出:将哈希表的键存入列表并排序,遍历排序后的列表,按顺序输出索引和对应的合并数值。



京公网安备 11010502036488号