题目概述
用栈实现队列。
题目要求用两个栈,实现队列的基本操作:push, pop, peek, empty。push的操作是在队尾添加元素,pop和peek则都需要在队首操作。
要求均摊时间在O(1), 也就是n个元素的用时控制在O(n)。
题目地址:https://leetcode-cn.com/leetbook/read/queue-stack/gvtxe/
一、解题思路
因为给出可以使用两个栈的条件,那么一个用来顺序存储元素,另一个用来逆序存储元素。
因为均摊时间要在O(1),那么逆序存储就控制在某个步骤就好了,不能瞎折腾。push这个操作天然可爱,就保持stack的顺序好啦,pop和peek是我们要关注的点。当逆序栈为空的时候,我们需要把顺序栈里的元素倒入逆序栈才能pop或者peek,这个倾倒的操作如果 pop完成了,peek就捡现成的啦,如果peek完成了,pop也是坐享其成,真是好搭档啊!
二、作业记录
1.作业代码
代码如下:
class MyQueue {
Stack<Integer> in = new Stack<Integer>();
Stack<Integer> out = new Stack<Integer>();
/** Initialize your data structure here. */
public MyQueue() {
in = new Stack();
out = new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if( !out.isEmpty()){
return out.pop();
}else{
while( !in.isEmpty()){
out.push( in.pop());
}
return out.pop();
}
}
/** Get the front element. */
public int peek() {
if( !out.isEmpty()){
return out.peek();
}else{
while( !in.isEmpty()){
out.push( in.pop());
}
return out.peek();
}
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}
/**
* 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();
* boolean param_4 = obj.empty();
*/
2.作业表现
表现如下:
好像内存消耗还有进步空间。
复杂度分析
时间复杂度:均摊时间复杂度应该是O(1),因为每次只有当pop或者peek操作时out为空时需要从in栈倾倒元素到out栈,复杂度是O(m),m是in栈的元素个数,其余时间各种操作都是O(1),均摊下来时间复杂度是O(1)。
空间复杂度:虽然需要两个栈存储元素,但是元素不会重复存储,要么在in栈,要么在out栈,所以没有占用额外的存储,空间复杂度我个人觉得是O(1)。