题目描述:设计一个最小栈,能够实现如下功能:
- push(x) – Push element x onto stack.(元素 x 进栈)
- pop() – Removes the element on top of the stack.(栈顶元素出栈)
- top() – Get the top element.(获得栈顶元素)
- getMin() – Retrieve the minimum element in the stack.(获取栈中元素的最小值)
解题思路:维护两个栈,一个栈实现进栈,出栈,获取栈顶元素的功能,另一个栈实现查找栈中最小元素的功能。
C++实现如下:
class MinStack {
public:
stack<int> allStack;
stack<int> minStack;
void push(int x)
{
if (allStack.empty())
{
allStack.push(x);
minStack.push(x);
}
else
{
allStack.push(x);
if (minStack.top() >= x) //一定是大于等于
minStack.push(x);
}
}
void pop()
{
if (allStack.top() == minStack.top())
{
minStack.pop();
}
allStack.pop();
}
int top()
{
return allStack.top();
}
int getMin()
{
return minStack.top();
}
};