题目描述
设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。
- push(x)–将元素x插入栈中
- pop()–移除栈顶元素
- top()–得到栈顶元素
- getMin()–得到栈中最小元素
样例
minStack.push(-1);
minStack.push(3);
minStack.push(-4);
minStack.getMin(); --> Returns -4.
minStack.pop();
minStack.top(); --> Returns 3.
minStack.getMin(); --> Returns -1.
解题思路
-
描述
使用一个辅助栈——单调栈,即可解决问题。
-
实现代码:
struct MinStack { stack<int> stack,minstack; MinStack() { } void push(int x) { stack.push(x); // 当minstack为空,直接压入栈。当minstack顶部元素与x相等时,同样需要插入。 if (minstack.empty() || (minstack.top() >= x)) { minstack.push(x); } } void pop() { // 两个栈顶元素相同,minstack需弹栈 if (minstack.top() == stack.top()) { minstack.pop(); } stack.pop(); } int top() { return stack.top(); } int getMin() { return minstack.top(); } };