The PriorityQueue class provides the functionality of the heap data structure. It implements the Queue interface.
Unlike normal queues, priority queue elements are retrieved in sorted order.
Suppose, we want to retrieve elements in ascending order. In this case, the head of the priority queue will be the smallest element. Once this element is retrieved, the next smallest element will be the head of the queue.
It is important to note that the elements of a priority queue may not be sorted. However, elements are always retrieved in sorted order.
In order to create a priority queue, we must import the java.util.PriorityQueue package. Once we import the package, here is how we can create a priority queue in Java.
PriorityQueue<Integer> numbers = new PriorityQueue<>();
Here, we have created a priority queue without any arguments. In this case, the head of the priority queue is the smallest element of the queue. And elements are removed in ascending order from the queue.
However, we can customize the ordering of elements with the help of the Comparator interface. We will learn about that later in this series.
The PriorityQueue class provides the implementation of all the methods present in the Queue interface.
You need to think of a data structure and implement it such that it can help you in answering the below-mentioned queries.
You are given Q queries, in each query you are given two integers x and y:
if x = 1 then insert the integer y to your data structure.
if x = 2 then print an integer denoting the minimum element currently present in your data-structure, if there are no elements present then print -1
if x = 3 then remove the minimum element currently present in your data structure, if there is no element present then don't do anything.
1 <= Q <= 105
1 <= x <= 3
1 <= y <= 1000
The first line of input contains a single integer Q.
Next, Q lines each contain two integers x and y for that query.
For each query in which x = 2 print its answer in separate lines.
6 2 -1 1 5 1 2 2 -1 3 -1 2 -1
-1 2 5
Query 1: x = 2 but as we don't have any element so we will print -1. Query 2: x = 1 we will insert 5 to our data structure. Query 3: x = 1 we will insert 2 to our data structure. Query 4: x = 2 the minimum element is 2 Query 5: x = 3 we will remove the minimum element i.e 2 Query 6: x = 2 the minium element now is 5