Get Min/Max in O(1) time from a Queue? [closed]

2020-02-25 22:50发布

How can I retrieve the max and min element from a queue at any time in 0(1) time complexity? Earlier I was using Collections.max and min to find the elements but that would be 0(n).

7条回答
神经病院院长
2楼-- · 2020-02-25 23:55

This isn't really a queue, but you can implement Min-Max Heap.

http://en.wikipedia.org/wiki/Min-max_heap

Basically, it's a heap which has it's max heap property at even levels, and min heap property at odd levels.

It has both O(1) MIN() and O(1) MAX() operations. However it's rather tricky to iterate, but it works and meets your requirements.

查看更多
登录 后发表回答