使用TreeMap来存储数据,可以省去排序操作。
public class Main {
static TreeMap<Integer, Integer> treemap = new TreeMap<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 0; i < n; i ++) {
int temp = in.nextInt();
treemap.put(temp, treemap.getOrDefault(temp, 0) + in.nextInt());
}
//下面是遍历TreeMap的方式
Iterator it = treemap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
int key = (Integer)entry.getKey();
int value = (Integer)entry.getValue();
System.out.println(key + " " + value);
}
in.close();
}
}