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.
设计一个堆支持push,pop,top和瞬间检索最小元素的功能。
学过数据结构就很简单了,而且c++专门有stack结构,代码如下:
class MinStack {
private:
stack<int> content;
stack<int> mins;
public:
void push(int x) {
content.push(x);
if(mins.empty() || x <= mins.top())
mins.push(x);
}
void pop() {
int top = content.top();
content.pop();
if(top == mins.top())
{
mins.pop();
}
}
int top() {
return content.top();
}
int getMin() {
return mins.top();
}
};