When should I use a TreeMap over a PriorityQueue and vice versa?

后端 未结 8 2174
南旧
南旧 2020-12-23 11:46

Seems they both let you retrieve the minimum, which is what I need for Prim\'s algorithm, and force me to remove and reinsert a key to update its value. Is there any advanta

8条回答
  •  长情又很酷
    2020-12-23 12:26

    It all depends what you want to achieve. Here are the main points to consider before you choose one over other.

    1. PriorityQueue Allows Duplicate(i.e with same priority) while TreeMap doesn't.
    2. Complexity of PriorityQueue is O(n)(when is increases its size), while that of TreeMap is O(logn)(as it is based on Red Black Tree)
    3. PriorityQueue is based on Array while in TreeMap nodes are linked to each other, so contains method of PriorityQueue would take O(n) time while TreeMap would take O(logn) time.

提交回复
热议问题