- [1. 题目信息](https://cloud.tencent.com/developer)
- [2. 解题](https://cloud.tencent.com/developer)
- [2.1 双栈](https://cloud.tencent.com/developer)
- [2.2 单栈](https://cloud.tencent.com/developer)
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
《剑指Offer》同题:面试题30. 包含min函数的栈
类似题目:LeetCode 716. 最大栈(双针 / list+map)
class MinStack {
list<int> stk;
list<int> min;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(min.empty()||min.front() >= x)
min.push_front(x);
stk.push_front(x);
}
void pop() {
if(stk.front()==min.front())
min.pop_front();
stk.pop_front();
}
int top() {
return stk.front();
}
int getMin() {
return min.front();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
class MinStack {
list<int> stk;
int curMin;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(stk.empty())
{
curMin = x;
}
else
{
curMin = stk.front();//之前没有写这句,当数据有pop时,curMin会变
if(x < curMin)
curMin = x;
}
stk.push_front(x);//数据在当前数据下最小值的下面
stk.push_front(curMin);//最小值在上
}
void pop() {
stk.pop_front();
stk.pop_front();
}
int top() {
int tmp = stk.front();
stk.pop_front();
int top = stk.front();
stk.push_front(tmp);
return top;
}
int getMin() {
return stk.front();
}
};
class MinStack {
stack<int> s;
int MIN;
int tp;
public:
/** initialize your data structure here. */
MinStack() {}
void push(int x) {
if(s.empty())
{
s.push(x);
s.push(x);
}
else
{
MIN = s.top() < x ? s.top() : x;
s.push(x);
s.push(MIN);
}
}
void pop() {
if(!s.empty())
{
s.pop();
s.pop();
}
}
int top() {
if(s.empty())
return -1;
MIN = s.top();
s.pop();
tp = s.top();
s.push(MIN);
return tp;
}
int min() {
if(s.empty())
return -1;
return s.top();
}
};