最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 20210305 LeetCode 每日一题,冲!|刷题打卡

    正文概述 掘金(小诸不是小猪)   2021-03-05   676

    题目描述

    Leetcode 链接:232. 用栈实现队列(easy)

    请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(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 操作)

    JavaScript 模板:

    /**
     * Initialize your data structure here.
     */
    var MyQueue = function() {
    
    };
    
    /**
     * Push element x to the back of queue. 
     * @param {number} x
     * @return {void}
     */
    MyQueue.prototype.push = function(x) {
    
    };
    
    /**
     * Removes the element from in front of queue and returns that element.
     * @return {number}
     */
    MyQueue.prototype.pop = function() {
    
    };
    
    /**
     * Get the front element.
     * @return {number}
     */
    MyQueue.prototype.peek = function() {
    
    };
    
    /**
     * Returns whether the queue is empty.
     * @return {boolean}
     */
    MyQueue.prototype.empty = function() {
    
    };
    
    /**
     * Your MyQueue object will be instantiated and called as such:
     * var obj = new MyQueue()
     * obj.push(x)
     * var param_2 = obj.pop()
     * var param_3 = obj.peek()
     * var param_4 = obj.empty()
     */
    

    思路分析

    吼吼今天的每日一题我又可以冲了!试了一下 JavaScript 自带的 push 和 shift,很快嘛,三行代码就搞定了,速度击败 99+,就是不太讲武德。下面我们正式开始吧。

    题目要求使用两个栈来模拟队列队列。我的想法是用一个 stackIn 栈来接收 push 进来的数据,用另一个 stackOut 栈来 shift(题目中为 pop)出队列中的数据。

    push 入队列的方法很简单,使用数组自带的 push 方法即可,主要的代码都集中在了 shift 的部分。

    在 shift 时,会先判断 stackOut 是否为空,若为空则会将 stackIn 部分的值一个一个传入 stackOut,然后 stackOut 的排序就会和 stackIn 原本的排序相反了。这时候 stackOut 就相当于一个反过来的队列,我们只需要 pop 其最后一个值即可,以下为实现部分:

    1. 初始化两个栈:
    var MyQueue = function() {
      this.stackIn = [];
      this.stackOut = [];
    };
    
    1. push 方法:
    MyQueue.prototype.push = function (x) {
      this.stackIn.push(x);
    };
    
    1. shift 方法:
    MyQueue.prototype.pop = function () {
      if (!this.stackOut.length) {
        while (this.stackIn.length) {
          this.stackOut.push(this.stackIn.pop());
        }
      }
      return this.stackOut.pop();
    };
    
    1. peek 方法:
    MyQueue.prototype.peek = function () {
      if (!this.stackOut.length) {
        while (this.stackIn.length) {
          this.stackOut.push(this.stackIn.pop());
        }
      }
      return this.stackOut[this.stackOut.length - 1];
    };
    

    时间复杂度为 O(1),虽然乍一看有一个 while 循环,不过其实每个元素最多只会出入栈两次;

    空间复杂度为 O(n),维护了两个栈

    优化一下

    我们其实可以发现 peek 和 pop 的部分拥有许多相同的代码,它们的目的都是为了将 stackIn 中的元素转入 stackOut。所以我们可以将这一部分提取出来,然后减少重复的代码:

    MyQueue.prototype.move = function() {
      if (!this.stackOut.length) {
        while (this.stackIn.length) {
          this.stackOut.push(this.stackIn.pop());
        }
      }
    }
    

    这样在 peek 和 pop 中的代码就更为简洁了:

    MyQueue.prototype.pop = function () {
      this.move();
      return this.stackOut.pop();
    };
    
    MyQueue.prototype.peek = function () {
      this.move();
      return this.stackOut[this.stackOut.length - 1];
    };
    

    完整代码

    /**
     * Initialize your data structure here.
     */
    var MyQueue = function () {
      this.stackIn = [];
      this.stackOut = [];
    };
    
    /**
     * Push element x to the back of queue.
     * @param {number} x
     * @return {void}
     */
    MyQueue.prototype.push = function (x) {
      this.stackIn.push(x);
    };
    
    /**
     * Removes the element from in front of queue and returns that element.
     * @return {number}
     */
    MyQueue.prototype.pop = function () {
      this.move();
      return this.stackOut.pop();
    };
    
    /**
     * Get the front element.
     * @return {number}
     */
    MyQueue.prototype.peek = function () {
      this.move();
      return this.stackOut[this.stackOut.length - 1];
    };
    
    /**
     * Returns whether the queue is empty.
     * @return {boolean}
     */
    MyQueue.prototype.empty = function () {
      return !this.stackOut.length && !this.stackIn.length;
    };
    
    MyQueue.prototype.move = function () {
      if (!this.stackOut.length) {
        while (this.stackIn.length) {
          this.stackOut.push(this.stackIn.pop());
        }
      }
    };
    
    /**
     * Your MyQueue object will be instantiated and called as such:
     * var obj = new MyQueue()
     * obj.push(x)
     * var param_2 = obj.pop()
     * var param_3 = obj.peek()
     * var param_4 = obj.empty()
     */
    
    

    总结一下

    今天的 LeetCode 每日一题可以稍微放松一下了 ( •̀ ω •́ )✧

    小伙伴们一起来用 JavaScript 刷算法吧:LeetCode-JavaScript

    本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情


    起源地下载网 » 20210305 LeetCode 每日一题,冲!|刷题打卡

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元