题目描述
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack 类:
MinStack() 初始化堆栈对象。
void push(int val) 将元素val推入堆栈。
void pop() 删除堆栈顶部的元素。
int top() 获取堆栈顶部的元素。
int getMin() 获取堆栈中的最小元素。
示例 1:
输入 :
"MinStack","push","push","push","getMin","pop","top","getMin"
\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]
输出 :
null,null,null,null,-3,null,0,-2
解释 :
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
提示:
−231<=val<=231−1-2^{31} <= val <= 2^{31} - 1−231<=val<=231−1
pop、top 和 getMin 操作总是在 非空栈 上调用
push, pop, top, and getMin最多被调用 3∗1043 * 10^43∗104 次
思路
手写一个栈+最小前缀和。
代码
cpp
struct node{
node(int value, int min_value, node *next) : _value(value), _min_value(min_value), _next(next){}
int _value;
int _min_value;
node* _next;
};
class MinStack {
public:
MinStack()
{
_top = nullptr;
}
void push(int val)
{
node *cur = new node(val, val, nullptr);
if(_top == nullptr)
{
_top = cur;
}
else
{
cur->_next = _top;
cur->_min_value = min(cur->_min_value, _top->_min_value);
_top = cur;
}
}
void pop()
{
node *cur = _top;
_top = _top->_next;
delete cur;
}
int top()
{
return _top->_value;
}
int getMin()
{
return _top->_min_value;
}
node *_top;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/