【题目描述】
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.
一开始没看懂,后来参考了别人的代码发现就是实现带min函数的stack的基本操作,用两个栈来表示,一个s作为正常栈,另一个mins保存最小值。
【代码】
class MinStack {
public:
stack<int> s;
stack<int> mins;
void push(int x) {
s.push(x);
if(mins.empty()||x<=mins.top()){
mins.push(x);
}
}
void pop() {
int n=s.top();
s.pop();
if(mins.top()==n) mins.pop();
}
int top() {
return s.top();
}
int getMin() {
return mins.top();
}
};
390

被折叠的 条评论
为什么被折叠?



