合并集
合并表记录
http://www.nowcoder.com/questionTerminal/de044e89123f4a7482bd2b214a685201
按照注释的流程
主要使用的就是hashmap,可以解决键唯一的问题
使用arraylist来排序,collections.sort得到升序
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
// 读取数据量
int times = scanner.nextInt();
HashMap<Integer, Integer> hasmap = new HashMap();
// 读取键和值
for(int i = 0; i < times; i++){
int key = scanner.nextInt();
int value = scanner.nextInt();
// 如果键已经存在,就在原基础上进行累加
if(hasmap.containsKey(key)){
hasmap.put(key, hasmap.get(key) + value);
// 如果键不存在,就直接添加
}else{
hasmap.put(key, value);
}
}
// 把所有的键存入arraylist,使用sort排序
ArrayList<Integer> result = new ArrayList<>();
for(int i : hasmap.keySet()){
result.add(i);
}
Collections.sort(result);
// 按照升序的键,进行打印
for(int i : result){
System.out.println(i+" "+hasmap.get(i));
}
}
}
