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,一个存放所有值,一个存放数值前面的最小值
class MinStack {
public:
stack<int> ms;
stack<int> mms;
void push(int x) {
ms.push(x);
if(mms.empty()||(!mms.empty()&& x<=mms.top()))
{
mms.push(x);
}
}
void pop() {
if(!ms.empty())
{
if(ms.top()==mms.top())
{
mms.pop();
}
ms.pop();
}
}
int top() {
if(!ms.empty())
{
return ms.top();
}
}
int getMin() {
if(!mms.empty())
{
return mms.top();
}
}
};