题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size=in.nextInt();
PriorityQueue<Integer> queue=new PriorityQueue<>();
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<size;i++){
int key=in.nextInt();
int value=in.nextInt();
//把对应的键值对存到map中
if(map.containsKey(key)){
map.put(key,map.get(key)+value);
}else{
map.put(key,value);
}
//同时在queue中加入当前key
queue.offer(key);
}
while(!queue.isEmpty()){
//如果当前queue队首元素还在map中,说明该元素没有被输出
if(map.get(queue.peek())!=null){
System.out.println(queue.peek()+" "+map.get(queue.peek()));
//输入key以后就删除这个key
map.remove(queue.poll());
continue;
}
//输出过的直接出队
queue.poll();
}
}
}