题目描述:
数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
Java实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int s=sc.nextInt();
int value=sc.nextInt();
if (map.containsKey(s)) {
map.put(s, map.get(s) + value);
} else
map.put(s, value);
}
for (Integer key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
}
}
}
知识点:
- HashMap是无序的,TreeMap是有序的
- TreeMap基于红黑树(Red-Black tree)的
NavigableMap
实现。该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的Comparator
进行排序,具体取决于使用的构造方法。