Heap 堆(优先队列)

A heap:

  • Stores elements, and can find the smallest (min-heap) or largest (max-heap) element stored in O(1).
  • Can add elements and remove the smallest (min-heap) or largest (max-heap) element in O(log(n)).
  • Can perform insertions and removals while always maintaining the first property.

PriorityQueue in Java

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
The head of this queue is the least element with respect to the specified ordering

Opeartions

  • void offer()
  • Object poll()
  • int size()
  • boolean isEmpty()

TreeSet in Java

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface.

Opeartions

  • void add()
  • E lower(E e)
  • E floor(E e)
  • E ceiling(E e)
  • E higher(E e)

用法

  1. 直接,当作排序数组
  2. Dijkstra,求单源最短路径
  3. 一边压入,比较另一边

刷题

三思

其他

参考