写在前面
最近刷阿里的题库,看到了一道用栈实现最小堆的题目,然后就找到了一系列栈模拟其他数据结构的题目,这里整理一下。这些题目对熟悉这些基本的数据结构帮助很大。
232. 用栈实现队列
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
- 你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
- 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
解法:
其实就是用栈实现一个队列的操作,这里需要搞清楚的就是两个数据其实是完全相反的,这也是这题的难点所在:
- 栈:LIFO 后进先出
- 队列:FIFO 先进先出
受到 @liweiwei 大佬的启发,其实可以发现两个数据结构就是反了过来,那么使用两个栈,一个栈(stackPush)用于元素进栈,一个栈(stackPop)用于元素出栈;
pop() 或者 top() 的时候:
- 如果 stackPop 里面有元素,直接从 stackPop 进行pop()和top()操作。
- 如果 stackPop 里面没有元素,一次性将 stackPush 里面的所有元素倒入 stackPop。
代码:
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> spop;
stack<int> spush;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
spush.push(x);
}
void shift(){//倒进去的过程,用函数单独写,简化代码
if(spop.empty()){//只有空的之后才开始倒,因为空的时候意味着栈底没有元素了
while(!spush.empty()){
spop.push(spush.top());
spush.pop();
}
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
shift();
int tmp = spop.top();
spop.pop();
return tmp;
}
/** Get the front element. */
int peek() {
shift();
return spop.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return (spop.empty()&&spush.empty());
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
155. 最小栈
设计一个支持 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.
解法:
因为有个getMin函数,而且要求在O(1)时间完成,所以需要再维护一个栈,这个栈的栈顶是最小值。
最小值栈的维护,分两种,同步数据和不同步数据,差别其实不大而且思路是一致的:
- 当最小值栈为空时,直接插入新元素
- 当最小值栈栈顶大于等于新元素,插入新元素。
同步和不同步就是在空间上面有细微差异,同步的栈会有无用元素,不同步的话会多一些边界计算,性能上面有细微差异。
代码(同步):
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s;
stack<int> helper;
MinStack() {
}
void push(int x) {
s.push(x);
if(helper.empty() || helper.top()>=x)
helper.push(x);
else
helper.push(helper.top());//同步
}
void pop() {
if(!s.empty()){
s.pop();
helper.pop();
}
}
int top() {
if(!s.empty())return s.top();
return 0;
}
int getMin() {
if(!helper.empty())return helper.top();
return 0;
}
};
/**
* 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 {
public:
/** initialize your data structure here. */
stack<int> s;
stack<int> helper;
MinStack() {
}
void push(int x) {
s.push(x);
if(helper.empty() || helper.top()>=x){
helper.push(x);
}
}
void pop() {
if(!s.empty()){
if(!helper.empty()&&s.top()==helper.top()){
helper.pop();
}
s.pop();
}
}
int top() {
if(!s.empty())return s.top();
return 0;
}
int getMin() {
if(!helper.empty())return helper.top();
return 0;
}
};
/**
* 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();
*/
716. 最大栈
设计一个最大栈,支持 push、pop、top、peekMax 和 popMax 操作。
- push(x) – 将元素 x 压入栈中。
- pop() – 移除栈顶元素并返回这个值。
- top() – 返回栈顶元素。
- peekMax() – 返回栈中最大元素。
- popMax() – 返回栈中最大的元素,并将其删除。如果有多个最大元素,只要删除最靠近栈顶的那个。
样例 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
注释:
- -1e7 <= x <= 1e7
- 操作次数不会超过 10000。
- 当栈为空的时候不会出现后四个操作。
解法:
双栈
这题和最小栈那题很像,但是多了一个popmax的操作,就复杂了很多,意味着要找到max并删除,这题就有这一个难点,需要一个临时栈实现这个popmax。
代码:
class MaxStack {
public:
/** initialize your data structure here. */
stack s;
stack maxs;
MaxStack() {
}
void push(int x) {
s.push(x);
if(maxs.empty()||x>=maxs.top())
maxs.push(x);
}
int pop() {
int tmp = s.top();
s.pop();
if(maxs.top()==tmp) maxs.pop();
return tmp;
}
int top() {
return s.top();
}
int peekMax() {
return maxs.top();
}
int popMax() {
stack<int> buffer;
int maxn = maxs.top();
maxs.pop();
while(s.top()!=maxn){
buffer.push(s.top());
s.pop();
}
s.pop();
while(!buffer.empty()){
push(buffer.top());//这里如果用s.push就会重复调用,所以直接push
buffer.pop();
}
return maxn;
}
};
/**
- Your MaxStack object will be instantiated and called as such:
- MaxStack* obj = new MaxStack();
- obj->push(x);
- int param_2 = obj->pop();
- int param_3 = obj->top();
- int param_4 = obj->peekMax();
- int param_5 = obj->popMax();
*/
用了两个栈,还要O(N)的时间,就很难受,所以我们要再想想有没有更优的解法。
平衡树+链表
平衡树中的每一个节点存储一个键值对,其中“键”表示某个在栈中出现的值,“值”为一个列表。时间复杂度:O(log(n))
代码:
class MaxStack {
public:
/** initialize your data structure here. */
list<int> l;
map<int, vector<list<int>::iterator>> mp;
MaxStack() {
}
void push(int x) {
l.push_front(x);
mp[x].push_back(l.begin());
}
int pop() {
int key = l.front();
mp[key].pop_back();
if(mp[key].empty()) mp.erase(key);
l.pop_front();
return key;
}
int top() {
return l.front();
}
int peekMax() {
//rbegin() 返回一个逆序迭代器,它指向容器的最后一个元素
return mp.rbegin()->first;
}
int popMax() {
int key = mp.rbegin()->first;
auto it = mp[key].back();
mp[key].pop_back();
if(mp[key].empty()) mp.erase(key);
l.erase(it);
return key;
}
};