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.
Solution in C++:
class MinStack {
public:
vector<int> stack;
int min;
MinStack(){
min = INT_MAX;
}
void push(int x) {
stack.push_back(x);
if(x<min) min=x;
}
void pop() {
int dele;
if(stack.size()>0){
dele = stack[stack.size()-1];
stack.pop_back();
}
if(dele==min){
min = INT_MAX;
for(int i=0; i<stack.size(); i++)
min=min<=stack[i]?min:stack[i];
}
}
int top() {
return stack[stack.size()-1];
}
int getMin() {
return min;
}
};

本文介绍了一个支持 push、pop、top 和获取最小元素的栈的设计,重点在于实现这些操作在常数时间内完成。
5万+

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



