简体   繁体   English

这个priorityQueue的时间复杂度是多少

[英]What is the time complexity of this priorityQueue

I have the below code, I wanted to know what is the time complexity of this code when I am using PriorityQueue.我有下面的代码,我想知道当我使用 PriorityQueue 时这段代码的时间复杂度是多少。

I have a listOfNumbers of size N我有一个大小为 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
}

As per this post: Time Complexity of Java PriorityQueue (heap) insertion of n elements?根据这篇文章: Java PriorityQueue(堆)插入n个元素的时间复杂度?

O(log n) time for the enqueing and dequeing methods (offer, poll, remove() and add)入队和出队方法(offer、poll、remove() 和 add)的 O(log n) 时间

Now how to calculate the time when I am adding the element back to Queue again.现在如何计算我再次将元素添加回队列的时间。

The running time of your program is log(n) + log(n-1) +... + log(1).你的程序的运行时间是 log(n) + log(n-1) +... + log(1)。

This is log(n.) (by repeated application of the log rule log(a) + log(b) = log(ab)).这是 log(n.)(通过重复应用日志规则 log(a) + log(b) = log(ab))。

log(n!) is Theta(n log n) see Is log(n?) = Θ(n·log(n))? log(n!) is theta(n log n) 请参见Is log(n?) = Θ(n·log(n))?

So your program runs in Theta(n log n) time.所以你的程序在 Theta(n log n) 时间内运行。

On q.add(q.poll()+q.poll());q.add(q.poll()+q.poll()); the number of element in queue is always O(N).队列中的元素数始终为 O(N)。 So, the enqueue still works in O(log(N)).所以,入队仍然在 O(log(N)) 中工作。

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

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