I'm implementing a queue class that has both a popMin and popMax method. So far I have it working with two priority queues, but even though a remove is log(n) time, I have to remove from the other queue as well which is linear. I know that a double ended priority queue can be implemented using a binary heap, but if I'm not mistaken that takes linear time to build? Is there a way I can do it more efficiently? I can only use Java library classes as well.
static class MinMaxQueue {
PriorityQueue<String> MinQueue = new PriorityQueue<String>();
PriorityQueue<String> MaxQueue = new PriorityQueue<String>(Collections.reverseOrder());
void push(String val) {
MinQueue.add(val);
MaxQueue.add(val);
}
String popMin() {
MaxQueue.remove(MinQueue.peek());
return MinQueue.remove();
}
String popMax() {
MinQueue.remove(MaxQueue.peek());
return MaxQueue.remove();
}
int size() {
return MinQueue.size();
}
}