Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Java, How do I peek() the top k elements in a PriorityQueue ?

I see in the documentation, that PriorityQueue.peek() gives me access to the head of the queue in O(1), but what if I need access to the k top elements in the queue ? I would use poll() k times, but that takes O(log(N)) , is there a way to do it in constant time ?

like image 565
Leo Avatar asked Oct 29 '25 19:10

Leo


1 Answers

Nope. If you could do it in constant time, you could do a comparison sort in linear time by heapifying an array and then finding the top N items, where N is all of them.

like image 93
user2357112 supports Monica Avatar answered Nov 01 '25 10:11

user2357112 supports Monica