Interview training O (1) Time to obtain the minimum element in the stack

Source: Internet
Author: User

This topic is very classic in Haitao's book. Let me do it directly.

My idea is to use an auxiliary stack to push an element into the stack when it is smaller than the minimum element of the current auxiliary stack, and record the number of elements in the stack when every minimum value is pushed into the stack.

For example, the stack sequence is 5, 7, 8, 2, and 1.

The secondary stack is in the form of 5 (1) 3 (1) 2 (1) 1 (1). Therefore, I am using a secondary stack and adding an auxiliary variable, therefore, when the original pop Stack was used, I reduced the number of auxiliary stack variables by 1.

5 (2) 3 (2)

If the value is 0, the stack is output.

After reading the ideas of Haitao, I am suddenly enlightened. The Ox is the ox.

The idea is that if the element inserted to the original stack is greater than the minimum element of the current secondary stack, the secondary stack will still push the current minimum element, which is too cool.

Original stack 5 7 3 8 2 1

Auxiliary stack 5 5 3 3 2 1

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.