Java集合之PriorityQueue

PriorityQueue

  • 定义
C++:priority_queue 
Java:PriorityQueue
  • 创建与其基本操作
创建:
PriorityQueue<Integer>=new PriorityQueue<>();
基本操作:
1	boolean isEmpty() 测试堆栈是否为空。
2	Object peek( ) 查看堆栈顶部的对象,但不移除。
3	Object poll( ) 移除堆栈顶部的对象,并返回该对象。
4	Object offer(Object element)

Java默认小根堆,如果想变大根堆有两种办法

  1. 类实现Comparable接口,实现compareTo方法
  2. 定义一个比较器类实现Comparator接口,实现compare方法

例题:HIHOCODER 1105
自己实现堆链接:http://www.cnblogs.com/zsyacm666666/p/7347440.html

方法1:

import java.util.*;
import java.io.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		PriorityQueue<Integer>que=new PriorityQueue<Integer>((int)1e5+10,new Comparator<Integer>(){
			@Override
			public int compare(Integer a1,Integer a2) {
				if(a1.equals(a2)) return 0;
				return a1.compareTo(a2)>0?-1:1;
			}
		});
		char op;
		int n=sc.nextInt(),x;
		while(n--!=0) {
			op=sc.next().charAt(0);
			if(op=='A') {
			     x=sc.nextInt();
			     que.offer(x);
			}else {
				out.println(que.poll());
			}
		}
		out.flush();
	}
}

方法2:

import java.util.*;
import java.io.*;
public class Main {
	static class node implements Comparable<node>{
		public int x;
        public node(int tx){
        	x=tx;
        }
		@Override
		public int compareTo(node o) {
		     if(x==o.x) return 0;
		     return x>o.x?-1:1;
		}
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		PriorityQueue<node>que=new PriorityQueue<node>();
		char op;
		int n=sc.nextInt(),x;
		while(n--!=0) {
			op=sc.next().charAt(0);
			if(op=='A') {
			     x=sc.nextInt();
			     que.add(new node(x));
			}else {
				out.println(que.poll().x);
			}
		}
		out.flush();
	}
}
原文地址:https://www.cnblogs.com/zsyacm666666/p/7656652.html