Java的优先队列默认是小根堆
import java.util.PriorityQueue;
public class Zz {
public static void main(String[] args) throws Exception{
PriorityQueue<Integer>a=new PriorityQueue<>();int x;Scanner cin=new Scanner (System.in);for(int i=1;i<=10;i++){
x=cin.nextInt();a.add(x);System.out.print(a.peek()+" ");//小根堆思想,每次输出一个堆中最小的数} }
/*1 -1 -2 -3 10 -4 -5 -6 -7 -8 1 -1 -2 -3 -3 -4 -5 -6 -7 -8 */}
下面是Java优先队列大根堆的使用:
(1)用Collections接口 <推荐>
import java.util.Collections;import java.util.PriorityQueue;
public class Zz {
public static void main(String[] args) throws Exception{
//PriorityQueue<Integer>a=new PriorityQueue<>();PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());int x;Scanner cin=new Scanner (System.in);for(int i=1;i<=10;i++){
x=cin.nextInt();queue.add(x);System.out.print(queue.peek()+" ");//大根堆思想,每次输出一个堆中最大的数} }
/*1 -1 -2 -3 10 -4 -5 -6 -7 -8 1 1 1 1 10 10 10 10 10 10 */}
(2)自定义sort
PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;}});
倒序输出大根堆:
public class Zz {
public static void main(String[] args) throws Exception{
//PriorityQueue<Integer>a=new PriorityQueue<>();PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;}});queue.offer(20);queue.offer(10);queue.offer(15);while(!queue.isEmpty()){
int t=queue.poll();System.out.println(t);}}
}
/*20 15 10 `