题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.*; public class Main { public static void main(String[] args) { HashMap<Integer, Integer> dataset = new HashMap<>(); Scanner in = new Scanner(System.in); int count = in.nextInt(); int key; int value; for (int i = 0; i < count; i++) { key = in.nextInt(); value = in.nextInt(); if (!dataset.containsKey(key)) { dataset.put(key, value); } else { dataset.put(key, value + dataset.get(key)); } } in.close(); // 用keySet构造TreeSet的时候,就已经可以获取排序(升序)之后的Set TreeSet<Integer> keySet = new TreeSet<>(dataset.keySet()); for (int k : keySet) { System.out.println(k + " " + dataset.get(k)); } } }