public class MinQueue {
Queue<Integer> data = new LinkedList<Integer>();
Deque<Integer> minData = new LinkedList<Integer>();
public void offer(Integer val){
data.offer(val);
while(!minData.isEmpty() && minData.peekLast() > val){
minData.pollLast();
}
minData.offerLast(val);
}
public Integer poll(){
if(data.isEmpty()) return null;
Integer peek = data.peek();
Integer minPeek = minData.peekFirst();
if(peek == minPeek){
minData.pollFirst();
}
return data.poll();
}
public Integer getMin(){
return minData.peek();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MinQueue mq = new MinQueue();
mq.offer(2);
System.out.println(mq.getMin());
mq.offer(3);
System.out.println(mq.getMin());
mq.offer(8);
System.out.println(mq.getMin());
mq.offer(4);
System.out.println(mq.getMin());
mq.poll();
mq.poll();
System.out.println(mq.getMin());
}
}
No comments:
Post a Comment