Nine Chapters count judges Net-original website
Http://www.jiuzhang.com/problem/50/
Topics
? In the " nine-chapter algorithm surface test 23 stack on the implementation of the Min function ", we introduced the implementation of an O (1) on the stack of the Min method. So, how do you implement a Min method on a queue?
Requires that the queue, in addition to the method that supports the basic push (x) Pop (), also needs to support the Min method, returning the smallest element in the current queue. The averaging complexity of each method is O (1)
Answer
In the ninth chapter of the question 49, "using the stack to implement the queue" and the question 23 "The implementation of the Min function on the stack", we explained how to implement the queue with the stack and implement the Min function on the stack. Then the solution of the two questions is how to implement the Min function in the queue. The brief steps are as follows:
Queue.push (x):
Minstack1.push (x)
Queue.pop ():
If Minstack2.empty ():
While (! Minstack1.emPty ()):
Minstack2.push (Minstack1.pop ())
Return Minstack2.pop ()
Queue.min ():
return min (Minstack1.min (), Minstack2.min ())
Nine-chapter algorithm surface question 50 implement min function on queue