leetcode155、最小值栈
作者:
残剑天下论 | 来源:发表于
2020-05-14 14:54 被阅读0次class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
// 同时更新数据栈和最小值栈
// 如果数据栈为空
if (_data.empty())
{
// 条件最后将x压入到数据栈中
// 此处更新最小值栈
// 直接将x压入到最小值栈中,就是当前最小
_temp.push(x);
}
else
{
// 如果数据栈不为空,则需要比较,比较后将最小值更新为最小值栈顶部元素
if (x < _temp.top())
{
_temp.push(x);
}
else
{
_temp.push(_temp.top());
}
}
// 更新数据栈
_data.push(x);
}
void pop() {
// 同时弹出_data和_temp中的顶部元素,维持着最小值栈
_data.pop();
_temp.pop();
}
int top() {
return _data.top();
}
int getMin() {
return _temp.top();
}
private:
stack<int> _data; // 数据栈
stack<int> _temp; // 存储当前最小值的栈
};
int main()
{
MinStack minStack;
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
cout << "min: " << minStack.getMin() << endl;
minStack.pop();
cout << "top: " << minStack.top() << endl;
cout << "min: " << minStack.getMin() << endl;
return 0;
}
本文标题:leetcode155、最小值栈
本文链接:https://www.haomeiwen.com/subject/qwucohtx.html
网友评论