PriorityQueue<Integer> pq =newPriorityQueue<>(); pq.add(3); pq.add(4); pq.add(1); pq.add(2); //输出顺序 1 2 3 4 //使用比较器 PriorityQueue<Integer> pq =newPriorityQueue<>((a, b) -> b-a); pq.add(3); pq.add(4); pq.add(1); pq.add(2); //输出顺序 4 3 2 1 概述...
PriorityQueue<Integer>pq=newPriorityQueue<>();// 创建一个优先队列,元素类型为Integer 1. 如果想要使用自定义的比较规则,可以通过传入比较器实现: PriorityQueue<Integer>pq=newPriorityQueue<>((a,b)->b-a);// 创建一个基于降序排列的优先队列 1. 3. 添加元素到PriorityQueue 我们可以使用add()方法向优先队列...
*/publicclassPriorityQueueTest{publicstaticvoidmain(String[]args){// 创建一个PriorityQueuePriorityQueue<Integer>pq=newPriorityQueue<>();// 添加元素pq.offer(1);pq.offer(3);pq.offer(2);// 获取元素System.out.println(pq.poll());// 1System.out.println(pq.poll());// 2System.out.println(pq....
例如,如果我们想要实现一个PriorityQueue,其中元素是整数,根据它们的值进行排序,我们可以使用以下方法: PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder()); pq.add(5); pq.add(3); pq.add(8); while (!pq.isEmpty()) { System.out.println(pq.poll()); } 复制代码 在这个例子...
publicclassTest{publicstaticvoidmain(String[]args){PriorityQueue<Integer>pq=newPriorityQueue<Integer>();pq.offer(3);pq.offer(-6);pq.offer(9);//打印结果为[-6, 3, 9]System.out.println(pq);//打印结果为-6System.out.println(pq.peek());//打印结果为-6System.out.println(pq.poll());}} ...
PriorityQueue<Integer>pq=newPriorityQueue<>();// 创建一个优先队列对象 1. 步骤3:向队列中添加元素 这里使用add方法来向队列中添加元素,offer方法也是可以的,二者在功能上类似。 pq.add(5);// 向优先队列中添加元素 5pq.add(3);// 向优先队列中添加元素 3pq.add(8);// 向优先队列中添加元素 8pq.off...
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); 复制代码 添加元素:使用add()或offer()方法向PriorityQueue中添加元素,例如: pq.add(5); pq.offer(10); 复制代码 访问队首元素:使用peek()方法可以访问PriorityQueue的队首元素,即优先级最高的元素,例如: int first = pq.peek()...
while(!pq.isEmpty()) res.add(pq.dequeue().e); return res; } private static void printList(List<Integer> nums){ for(Integer num: nums) System.out.print(num + " "); System.out.println(); } public static void main(String[] args) { ...
(pq); } // 获取最小的 K 个元素(使用最大堆) public static List<Integer> topKMin(int[] nums, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b - a); // 自定义最大堆 for (int num : nums) { pq.offer(num); if (pq.size() > k) { pq.poll(); // ...
packagecn.juwatech.priorityqueue;importjava.util.PriorityQueue;publicclassPriorityQueueExample{publicstaticvoidmain(String[] args){// 创建一个PriorityQueue,默认使用自然顺序(升序)PriorityQueue<Integer> pq =newPriorityQueue<>();// 添加元素到队列pq.add(10); ...