简体   繁体   中英

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.

I have a listOfNumbers of size N

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?

O(log n) time for the enqueing and dequeing methods (offer, poll, remove() and add)

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).

This is log(n.) (by repeated application of the log rule log(a) + log(b) = log(ab)).

log(n!) is Theta(n log n) see Is log(n?) = Θ(n·log(n))?

So your program runs in Theta(n log n) time.

On q.add(q.poll()+q.poll()); the number of element in queue is always O(N). So, the enqueue still works in O(log(N)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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