LeetCode Min Stack

Source: Internet
Author: User

LeetCode Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • Push (x) -- Push element x onto stack.
  • Pop () -- Removes the element on top of the stack.
  • Top () -- Get the top element.
  • GetMin () -- Retrieve the minimum element in the stack.

    Show TagsHave you met this question in a real interview? Yes No

    Discuss

    Question: write a new stack: Support for inbound and outbound stacks, get the top of the stack, and get the minimum number of stacks at this time.

    Idea: the first three operations can be implemented using one stack. To minimize the number of operations, a new monotonous stack is required for maintenance. Note the following points for the new monotonous Stack: when the original stack pop drops a number, it may affect this monotonous stack. If the pop drops at this time, it can be solved if it is the top of the monotonous stack, because this monotonous stack is a subset of the original Stack


    class MinStack {public:    void push(int x) {        st.push(x);        if (stm.empty() || stm.top() >= x) stm.push(x);    }    void pop() {        int top = st.top();        st.pop();        if (top == stm.top()) stm.pop();    }    int top() {        return st.top();    }    int getMin() {        return stm.top();    }    private:        stack
       
         st;        stack
        
          stm;};
        
       


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.