用栈实现队列|刷题打卡

185 阅读3分钟

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

实现 MyQueue 类:

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

说明:

  • 你只能使用标准的栈操作 —— 也就是只有 push to toppeek/pop from topsize, 和 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 次 pushpoppeekempty
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

解题思路一

这道题主要是考虑栈和队列两个数据结构的不同。栈先进后出,而队列需要先进先出。也就是一个与原栈反向存储的栈,取出值的顺序就是队列的顺序。考虑有两个栈,只需要在每次取的时候将栈的值挨个取出来压入另一个栈,就可以实现栈的反向存储:

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
  this.stack = [];
  this.stack2 = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
  this.stack.push(x);
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
  while(this.stack.length){
    this.stack2.push(this.stack.pop());
  }
  const res = this.stack2.pop();
  while(this.stack2.length) {
    this.stack.push(this.stack2.pop());
  }
  return res;
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
  while(this.stack.length){
    this.stack2.push(this.stack.pop());
  }
  const res = this.stack2.pop();
  this.stack.push(res);
  while(this.stack2.length) {
    this.stack.push(this.stack2.pop());
  }
  return res;
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
  return this.stack.length === 0;
};

/**
 * 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()
 */

这里 peekpop 不同的就在于是不是要将取出来的元素压回原来的栈。

解题思路二

上面的方法可以解决问题,可是每次 pop 或者 peek 的时候都需要把栈里所有的元素来回“倒”一次。当元素很多的时候,就会非常花时间。有没有办法能简化呢?

仔细观察上面的代码,发现每次 poppeek 的值的时候,都需要把原栈的值“倒入”第二个栈,取到值以后再“倒回去”。但其实连续取值的话,发现第二个栈连续 pop 的值就是想要的数列的先进的值,所以不需要把第二个栈的值“倒回”第一个栈,只需要在第二个栈有值的情况下去 pop 就好,直到没值的时候再去第一个栈里面“倒”。

直观一些,我们给第二个栈取名叫outStak, 第一个栈取名叫inStack。表明一个负责进,一个负责出。

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
  this.inStack = [];
  this.outStack = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
  this.inStack.push(x);
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
  if(!this.outStack.length) {
    while(this.inStack.length){
      this.outStack.push(this.inStack.pop());
    }
  }
  const res = this.outStack.pop();
  return res;
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
  const res = this.pop();
  this.outStack.push(res);
  return res;
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
  return this.inStack.length === 0 && this.outStack.length === 0;
};

/**
 * 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()
 */

总结

这道题对于熟悉栈和队列数据结构的同学难度不大,需要注意的就是像第一个解法一样傻傻的倒来倒去会更符合直觉,但是仔细想想就会发现有优化的空间,把两个栈的数据整体考虑,是一种思维习惯。

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