LeetCode刷题之路-每日一题-232. 用栈实现队列

前言

今天周五,稍稍偷个懒。

题目描述


请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

进阶:

你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

示例:

输入:
[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

提示:

1 <= x <= 9
最多调用 100 次 push、pop、peek 和 empty
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)


解题思路

可能是收到前两天的用队列模拟栈的影响,思维固化在push方法中直接实现。每次添加元素,都需要将当前栈进行2次遍历,时间复杂度编程O(n^2)。
大致push实现思路如下:将当前以队列形式的stack0依次弹出放到stack1-还原添加的顺序,再往stack0中先添加当前元素,然后再依次将stack1中的元素添加到stack0. 此时栈就按照想要的队列的顺序了。
1 -> 1
2 -> 1 -> 2 1
3 -> 2 1 -> 1 2 -> 3 2 1
4 ->3 2 1 -> 1 2 3 -> 4 3 2 1

看了官方题解,释放思路:观察到上述思路中,发现中间有一个过程是将原本按照队列排列好的元素,做了2次遍历,那么,如果我们用一个栈记录下元素添加的顺序呢?如果按照之前的思路,在push中完成队列的构建,那么还是绕不开遍历2次。然后发现push刚好可以很方便的记录元素的添加顺序。那么是不是可以在弹出元素时,再将栈中的元素入队呢?
采用2个栈,一个在push中用来保存元素的添加顺序,另一个作为队列。在pop方法中,先将带入队的元素入队,然后再弹出队中的元素。那就只需要遍历一次元素!而且,也不是非得在push方法中实现。

解题代码


    /** Initialize your data structure here. */
    private Deque<Integer> stack0;
    private Deque<Integer> stack1;
    public MyQueue() {
        this.stack0 = new LinkedList<>();
        this.stack1 = new LinkedList<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
       stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        stack2queue(this.stack0,this.stack1);
        return stack0.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        stack2queue(this.stack0,this.stack1);
        return stack0.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack0.isEmpty() && stack1.isEmpty();
    }
    
    private void stack2queue(Deque<Integer> queue, Deque<Integer> stack) {
    	// 访问入参比访问成员快
        if (queue.isEmpty()) {
            while(!stack.isEmpty()){
                queue.push(stack.pop());
            }
        }
    }

总结

java.util.Stack 很笨重,每个方法都上锁了,所以相比于线程不安全的LinkedList要差好多。继承于Vector,而Vector是List,不是Deque,所以Stack自行实现了相关方法,也没有真正实现Deque接口。

LinkedList实现了List、Queue、Deque。
Deque是双端队列,因此可以很方便的模拟栈。
push是Deque的方法,是栈的方法。
peek是Queue的方法,是队列的方法。

访问入参比访问成员快

上一篇:华为服务器如何配置管理IP


下一篇:Stream中的Peek操作