题解 | 【模板】整数优先队列
【模板】整数优先队列
https://www.nowcoder.com/practice/a88e9711f7b04369982bbe8902278ae4
使用 TreeMap也可以实现排序和操作,注意删除只删除一个就好了。
或者直接使用优先队列实现。
import java.util.Scanner;
import java.util.TreeMap;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
// 按键排序,使用TreeMap
TreeMap<Integer, Integer> tm = new TreeMap<>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-- > 0) {
int op = sc.nextInt();
switch (op) {
case 1:
int x = sc.nextInt();
tm.put(x, tm.getOrDefault(x, 0) + 1);
break;
case 2:
// 查询操作
int minNum = tm.firstKey();
System.out.println(minNum);
break;
case 3:
// 删除操作
int minNum1 = tm.firstKey();
int cnt = tm.get(minNum1);
if (cnt > 1) {
tm.put(minNum1, cnt -1);
}else {
tm.remove(minNum1);
}
break;
}
}
}
}
优先队列实现,
import java.util.Scanner;
import java.util.PriorityQueue;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
// 优先队列实现,最小元素在队首
PriorityQueue<Integer> pq = new PriorityQueue<>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-- > 0){
int op = sc.nextInt();
switch (op) {
case 1:
// 插入操作
int x = sc.nextInt();
pq.offer(x);
break;
case 2:
// 查询操作
System.out.println(pq.peek());
break;
case 3:
// 删除操作
pq.poll();
break;
}
}
sc.close();
}
}
#Java#
