算法 1.4.1 用栈实现队列【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 操作)

数据结构

算法思维

  • 栈操作

解题要点

  • 栈的 LIFO 特性
  • 队列的 FIFO 特性

解题思路

一. Comprehend 理解题意
  • 需要自实现一个队列
  • 只能使用两个栈作为数据结构
  • 只能使用栈操作(push(x), pop(), peek(), isEmpty())来实现队列功能
二. Choose 选择数据结构与算法
解法一:两栈相互 压入/弹出 元素
  • 数据结构:栈
  • 算法思维:栈操作
三. Code 编码实现基本解法
class MyQueue {

    Stack < Integer > s1; //入队所用的 push 栈
    Stack < Integer > s2; //出队所用的 pop 栈

    /**
     * Initialize your data structure here.
     */
    public MyQueue() {
        s1 = new Stack < > ();
        s2 = new Stack < > ();
    }

    /**
     * Push element x to the back of queue.
     */
    public void push(int x) {
        //1.入队前,先将s2中的所有元素移入s1中
        while(!s2.isEmpty()) {
            s1.push(s2.pop());
        }
        //2.入队 == 入s1栈
        s1.push(x);
    }

    /**
     * Removes the element from in front of queue and returns that element.
     */
    public int pop() {
        //3.出队前,先将s1中的所有元素移入s2中
        while(!s1.isEmpty()) {
            s2.push(s1.pop());
        }
        //4.出队 == 出s2栈
        return s2.pop();
    }

    /**
     * Get the front element.
     */
    public int peek() {
        //5.查询队首,与出队类似,先将s1中的所有元素移入s2中
        while(!s1.isEmpty()) {
            s2.push(s1.pop());
        }
        //6.查询队首 == 查询s2栈顶
        return s2.peek();
    }

    /**
     * Returns whether the queue is empty.
     */
    public boolean empty() {
        //7.空队为空 == s1和s2同时为空
        return s1.isEmpty() && s2.isEmpty();
    }

}

执行耗时:0 ms,击败了 100.00% 的Java用户
内存消耗:36.1 MB,击败了 92.05% 的Java用户
时间复杂度:O(n2) -- 每次出入队都执行1次栈的遍历 O(n2),出入栈操作 O(1)
空间复杂度:O(n) -- 栈的内存空间 O(n)

四. Consider 思考更优解

优化代码结构
改变算法思维
借鉴其他算法

思路:
方法:
解法二:XXX
  • 数据结构:
  • 算法思维:
五. Code 编码实现最优解

执行耗时:
内存消耗:
时间复杂度:O() --
空间复杂度:O() --

六. Change 变形与延伸

=== 待续 ===

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容