![](/img/trans.png)
[英]What is the time complexity of constructing a PriorityQueue from a collection?
[英]What is the time complexity of this priorityQueue
我有下面的代码,我想知道当我使用 PriorityQueue 时这段代码的时间复杂度是多少。
我有一个大小为 N 的 listOfNumbers
Queue<Integer> q = new PriorityQueue<>();
q.addAll(listOfNumbers);
while(q.size()>1) {
q.add(q.poll()+q.poll()); // add sum of 2 least elements back to Queue
}
根据这篇文章: Java PriorityQueue(堆)插入n个元素的时间复杂度?
入队和出队方法(offer、poll、remove() 和 add)的 O(log n) 时间
现在如何计算我再次将元素添加回队列的时间。
你的程序的运行时间是 log(n) + log(n-1) +... + log(1)。
这是 log(n.)(通过重复应用日志规则 log(a) + log(b) = log(ab))。
log(n!) is theta(n log n) 请参见Is log(n?) = Θ(n·log(n))?
所以你的程序在 Theta(n log n) 时间内运行。
在q.add(q.poll()+q.poll());
队列中的元素数始终为 O(N)。 所以,入队仍然在 O(log(N)) 中工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.