优先级队列

优先队列的使用操作
Java中优先队列默认小根堆(先出来最小的元素)(c++默认大根堆)
package 优先级队列;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class Test {
static void TestPriorityQueue() {
PriorityQueue<Integer> q1 = new PriorityQueue<>();
//直接在优先队列中加入元素
q1.offer(1);
q1.offer(6);
q1.offer(2);
//可以弹出元素到集合中
ArrayList<Integer> list = new ArrayList<>();
while (!q1.isEmpty()) {
list.add(q1.poll());
}
System.out.println(list);
//可以在优先队列中加入集合
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(3);
list1.add(1);
list1.add(2);
PriorityQueue<Integer> q2 = new PriorityQueue<>(list1);
System.out.println(q2.size());
System.out.println(q2.peek());//不弹出打印
System.out.println(q2.poll());//弹出打印
System.out.println(q2.size());
}
public static void main(String[] args) {
TestPriorityQueue();
}
}
常见操作用法汇总

小根堆改成大根堆的排列方式
// 创建大根堆(降序优先队列)
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
// 示例使用
maxHeap.offer(5);
maxHeap.offer(2);
maxHeap.offer(8);
maxHeap.offer(1);
System.out.println(maxHeap.poll()); // 输出 8(最大值)
System.out.println(maxHeap.poll()); // 输出 5
System.out.println(maxHeap.poll()); // 输出 2
System.out.println(maxHeap.poll()); // 输出 1

浙公网安备 33010602011771号