Solution:
public static void main(String[] args) {
MinQueue queue = new MinQueue();
// Input 3 -> 1 -> 4 -> 2
queue.offer(3).offer(1).offer(4).offer(2);
// 0 0 0 1 1 1
while(queue.isEmpty() == false) {
System.out.println(queue.getMin());
queue.poll();
}
// Output should be 1 -> 1 -> 2 -> 2
}
static class MinQueue {
private Queue<Integer> mQueue = new LinkedList<>();
private Deque<Integer> mMinDeque = new ArrayDeque<>();
MinQueue offer(int val) {
int min = val;
while(!mMinDeque.isEmpty() && mMinDeque.getLast() > val) {
mMinDeque.pollLast();
min = val;
}
int size = mQueue.size() - mMinDeque.size();
for (int i = 0; i <= size; i++) {
mMinDeque.addLast(min);
}
mQueue.offer(val);
return this;
}
int poll() {
mMinDeque.poll();
return mQueue.poll();
}
boolean isEmpty() {
return mQueue.isEmpty();
}
int getMin() {
return mMinDeque.peek();
}
}
No comments:
Post a Comment