题目概述
用两个队列实现栈的基本操作push, top, pop,empty。均摊时间复杂度最好是O(1)
题目地址:https://leetcode-cn.com/leetbook/read/queue-stack/gw7fg/
一、作业思路
一开始,我还想着“用栈实现队列”和“用队列实现栈”应该差不过,思路可以借鉴,于是就顺着pop那个环节倒腾元素去了,结果绕了好久,终于发现还是在push环节把问题解决掉比较好。
因为要保证Last in first out, 而队列只能从头部out,我们在插入数据的时候必须保证last in的数据元素排在队首,也就是我们每次插入都必须保证在队列中逆序存储数据元素。也是因为顺序的重要性,我们每次操作之后都必须保证数据都存在一个队列里,否则顺序会乱。
其实我觉得用队列实现栈要比用栈实现队列难一些:
1)我们总是要保持一个队列为空,其实想到这一点我花了好久,一开始一直在想最后进的元素要存在哪一个队里(捂脸),陷入了栈的僵局。
2)数据需要倒两次,倒入备用的空队列之后,还得倒回来。其实也有想过要不引入一个临时变量吧,但是又怕不符合题目要求。
二、作业记录
1.作业代码
代码如下:
class MyStack {
Queue<Integer> in = new ArrayDeque<Integer>();
Queue<Integer> out = new ArrayDeque<Integer>();
/** Initialize your data structure here. */
public MyStack() {
in = new ArrayDeque<Integer>();
out = new ArrayDeque<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
if( out.isEmpty() ){
out.offer(x);
}else{
while(! out.isEmpty()){
in.offer(out.poll());
}
out.offer(x);
while( !in.isEmpty()){
out.offer(in.poll());
}
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return out.poll();
}
/** Get the top element. */
public int top() {
return out.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
2.作业表现
表现如下:
内存消耗有些大,是因为Queue的实现方式导致的吗?
把队列的实现方式换成LinkedList,结果稍有改观?:
复杂度分析
时间复杂度:均摊时间复杂度是O(1),最差的情况就是push全部数据元素进队列,倒腾两遍数据逆排序,时间复杂度是O(n)。其他操作都是O(1)的复杂度。
空间复杂度:数据没有重复存储,我个人认为空间复杂度也是O(1)。