栈是一种「先进后出」的数据结构。今天的题目要求设计一个最小栈,也就是说可以从栈中直接获取当前栈中最小的元素,时间复杂度为 O(1)。除此之外还需要支持栈的基本操作,push:向栈中插入元素、pop:移除栈顶元素、top: 获取栈顶元素。:
155. Min Stack
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.
分析
在做这道题前,先看看栈的基本结构:
接口的基本定义:
class Stack {
void push(E);
void pop();
E top();
int getSize();
boolean isEmpty();
}
在 C++ 中已经实现了这种数据结构,但是不能满足题目的要求 --- 获取最小元素。解这道题可以使用两个栈,一个(mainStack)用来存放所有的元素,一个(minStack)用来存放较小的元素。
push( int x ) 入栈:如果 x <= minStack 的 top 值或者 minStack 为空,则在 minStack 中加入 x,否则只在 mainStack 中加入 x;
pop( ) 出栈:如果 mainStack 的 top 与 minStack 的 top 相等,则minStack 和 mainStack 均 pop,否则只有 mainStack 执行 pop;
分析下图:
1. 5 入栈,minStack 为空,把 5 也插入到 minStack 中;
2. 3入栈,3 小于 minStack 的 top,把 3 也插入到 minStack 中;
3. 7入栈,7 大于 minStack 的 top,不入 minStack;
4. 1入栈,1 小于 minStack 的 top,把 1 也插入到 minStack 中;
5. 8入栈,8 大于 minStack 的 top,不入 minStack;
6. 0 入栈,0 小于 minStack 的 top,把 0 也插入到 minStack 中;
C++实现
class MinStack {
public:
// 主栈,保存了所有的元素
stack<int> mainStack;
// 保存比较小的元素
stack<int> minStack;
// 入栈
void push(int x) {
mainStack.push(x);
if (minStack.empty() || x <= getMin()) {
minStack.push(x);
}
}
// 出栈
void pop() {
if (mainStack.top() == getMin()) {
minStack.pop();
}
mainStack.pop();
}
// 栈顶
int top() {
return mainStack.top();
}
// 最小值
int getMin() {
return minStack.top();
}
};
算法实现比较简单,主要为了学习掌握栈的实际使用场景。栈还有其它很多使用场景,比如撤销操作,括号匹配等等。
推荐阅读:
图解算法