Priority Queue remove complexity time

前端 未结 3 1695
一向
一向 2020-12-05 09:51

What is the complexity (big-oh) for the remove() function on the Priority Queue class in Java? I can\'t find anything documented anywhere, I think it\'s O(n), c

相关标签:
3条回答
  • 2020-12-05 10:19

    The confusion is actually caused by your "remove" function. In java, there are two remove functions.

    1. remove() -> This is to remove the head/root, it takes O(logN) time.

    2. remove(Object o) -> This is to remove an arbitrary object. Finding this object takes O(N) time, and removing it takes O(logN) time.

    0 讨论(0)
  • 2020-12-05 10:20

    The complexity for remove is O(N) since the complexity for contains is O(N) (in java's priority queue class)

    One way this can be made O(logN) in your own Priority Queue implementation is to maintain an auxiliary data structure like a HashMap that maintains the mappings from a value in the priority queue to its position in the queue. So, at any given time - you would know the index position of any value.

    Note that this modification does not affect the running time of any of the existing operations - you would only need to update the mappings during the heapify operations.

    0 讨论(0)
  • 2020-12-05 10:33

    According to Oracle documentation: "Implementation note: this implementation provides O(log(n)) time for the enqueing and dequeing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size)."

    Link here to Oracle Doc

    0 讨论(0)
提交回复
热议问题