题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.io.*; import java.util.TreeMap; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; while ((str = br.readLine()) != null) { //将str转换为int类型的整数 int n = Integer.parseInt(str); //创建一个TreeMap集合 TreeMap<Integer, Integer> map = new TreeMap<>(); //循环读取键值对 for (int i = 0; i < n; i++) { //读取键值对,然后根据空格进行切分 String s = br.readLine(); String[] strings = s.split(" "); int key = Integer.parseInt(strings[0]); int value = Integer.parseInt(strings[1]); //将key value键值根据key进行累加 map.put(key, map.getOrDefault(key, 0) + value); } //创建一个字符串 StringBuilder sb = new StringBuilder(); //遍历整个map for (int i : map.keySet()) { System.out.println(i + " " + map.get(i)); } } } }