Is there a Heap in java?

后端 未结 6 1994
一整个雨季
一整个雨季 2021-01-31 13:00

I am porting a C++ library to Java and I need a heap data structure. Is there a standard implementation or will I need to do it myself?

6条回答
  •  日久生厌
    2021-01-31 13:59

    For Java 8, updating on an existing answer:

    You can use Java Priority Queue as a Heap.

    Min Heap: --> to keep the min element always on top, so you can access it in O(1).

    PriorityQueue minHeap = new PriorityQueue();
    

    Max Heap: --> to keep the max element always on top, the same order as above.

    PriorityQueue maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
    

    Which is the same as (Integer o1, Integer o2) -> (- Integer.compare(o1,o2)) as suggested from other answers.

    And you can use:
    add --> to add element to the queue. O(log n)
    remove --> to get and remove the min/max. O(log n)
    peek --> to get, but not remove the min/max. O(1)

提交回复
热议问题