-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueWithGetMin.java
More file actions
36 lines (30 loc) · 928 Bytes
/
Copy pathQueueWithGetMin.java
File metadata and controls
36 lines (30 loc) · 928 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package queue;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
public class QueueWithGetMin {
Queue<Integer> q = new LinkedList<>();
Deque<Integer> minQ = new ArrayDeque<>();
// Initially we add the data to the q
// if the minQ is not empty and the last element in the minQ is greater than data
// we remove the element till the data is small then the elements present the minq
// and at last we add the data to the minQ
void enqueue(int data) {
q.offer(data);
while (!minQ.isEmpty() && minQ.getLast() > data) {
minQ.pollLast();
}
minQ.offerLast(data);
}
void dequeue() {
if (q.isEmpty()) return;
int removed = q.poll();
if (removed == minQ.getFirst()) {
minQ.pollFirst();
}
}
int getMin() {
return minQ.getFirst();
}
}