Nine-chapter algorithm surface question 50 implement min function on queue

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.