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;};