题目:
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.
思路分析:
用两个stack来维护这个MinStack结构。1个stack用来正常进行stack的push pop等操作。另外1个stack用来维护min.每次对stack进行pop或者push时,也对min_stack进行相应操作。
C++代码示例:
#include <stack>using namespace std;class MinStack
{
private:stack<int> stk;stack<int> min;
public:void push(int x){stk.push(x);if (min.empty()){min.push(x);}else{//注意这里是>=,我第一次用>结果报错了if (min.top() >= x){min.push(x);}}}void pop(){if (stk.top() == min.top()){min.pop();}stk.pop();}int top(){return stk.top();}int getMin(){return min.top();}
};