简体   繁体   English

Java:有没有一种方法可以使用PriorityQueue从O(n)中的数组构造最大堆?

[英]Java: is there a way to construct a max-heap from an array in O(n) using PriorityQueue?

Correct me if I'm wrong, but I think the PriorityQueue(Collection c) constructor will create a min-heap from a collection in time O(n). 如果我错了,请纠正我,但是我认为PriorityQueue(Collection c)构造函数将在O(n)的时间内从集合中创建一个最小堆。 However, I couldn't find a constructor where I can pass both a collection and a comparator (in order to convert the min-heap to a max-heap). 但是,我找不到可以同时传递集合和比较器的构造函数(以便将最小堆转换为最大堆)。 So I was wondering if there is a way to construct a max-heap from an array (say, int array) in O(n) using PriorityQueue? 所以我想知道是否存在一种使用PriorityQueue从O(n)中的数组(例如int数组)构造最大堆的方法?

No, having a set of elements arranged in a min-heap does not provide any advantage for rearranging them into a max-heap. 不可以,将一组元素排列在最小堆中并不能为将它们重新排列为最大堆提供任何好处。 Also, you seem to be assuming that the PriorityQueue constructors that accept a collection have O(n) asymptotic complexity. 另外,您似乎假设接受集合的PriorityQueue构造函数具有O(n)渐近复杂度。 That's plausible -- even likely -- but it is not documented, so it is not safe to rely on it. 这是合理的,甚至可能的,但是没有记录,因此依赖它并不安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM