Is there a Heap in java?

后端 未结 6 1990
一整个雨季
一整个雨季 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:49

    Min heap:

    PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
    

    Max heap:

    PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return - Integer.compare(o1, o2);
        }
    });
    
    0 讨论(0)
  • 2021-01-31 13:50

    PriorityQueue uses a heap. Based on the oracle documentation at https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html it seems likely that it is an implementation of a binary heap. I don't think there is an official implementation of a fibonacci or pairing heap, though I'd love to see either one of the two available.

    0 讨论(0)
  • 2021-01-31 13:51

    In Java PriorityQueue can be used as a Heap.

    Min Heap

    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    

    Max Heap:

    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
    
    0 讨论(0)
  • 2021-01-31 13:54

    No as such there isn't but you can use Priority Queue as a Heap. Its officially told by Oracle to use Priority Queue as a Heap you can also refer to this link for further clarification.

    PriorityQueue<Integer> MinHeap = new PriorityQueue<>();
    
    PriorityQueue<Integer> MaxHeap = new PriorityQueue<>(Comparator.reverseOrder());
    
    0 讨论(0)
  • 2021-01-31 13:55

    You can also consider TreeSet, which guarantees log(n) time for basic operations (add, remove, contains).

    0 讨论(0)
  • 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<Integer> minHeap = new PriorityQueue<Integer>();
    

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

    PriorityQueue<Integer> 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)

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