Java中有堆吗?


Answers:


29

最小堆:

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

最大堆:

PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return - Integer.compare(o1, o2);
    }
});

24

对于Java 8,更新现有答案

您可以将Java Priority Queue用作堆。

Min Heap: ->使min元素始终位于顶部,因此您可以在O(1)中对其进行访问。

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

Max Heap: ->使max元素始终位于顶部,与上述顺序相同。

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

(Integer o1, Integer o2) -> (- Integer.compare(o1,o2))与其他答案所建议的相同。

您可以使用:
add->将元素添加到队列中。O(log n)
remove->获取和删除最小值/最大值。O(log n)
peek->获取,但不删除最小值/最大值。O(1)


10

在Java中,PriorityQueue可以用作堆。

最小堆

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

最大堆:

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


3

否,没有,但是您可以将Priority Queue用作堆。Oracle正式告知其使用Priority Queue作为堆,您也可以参考此链接进行进一步说明。

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

PriorityQueue<Integer> MaxHeap = new PriorityQueue<>(Comparator.reverseOrder());

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.