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

实现 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) ,即使其中一个操作可能花费较长时间。

示例

  1. 输入:
  2. ["MyQueue", "push", "push", "peek", "pop", "empty"]
  3. [[], [1], [2], [], [], []]
  4. 输出:
  5. [null, null, null, 1, 1, false]
  6. 解释:
  7. MyQueue myQueue = new MyQueue();
  8. myQueue.push(1); // queue is: [1]
  9. myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
  10. myQueue.peek(); // return 1
  11. myQueue.pop(); // return 1, queue is [2]
  12. myQueue.empty(); // return false

提示

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

题解

这题还是比较简单的。动态规划不会,这还不会吗?😽

用两个栈模拟即可,一个作为入栈,一个作为出栈。所有进入的元素,都放入入栈,如果有出栈操作,就把入栈中的元素全部弹入出栈即可。
1614908055-DRhjRN-232.gif

Python

  1. class MyQueue:
  2. def __init__(self):
  3. """
  4. Initialize your data structure here.
  5. """
  6. self.inStack=[]
  7. self.outStack=[]
  8. def push(self, x: int) -> None:
  9. """
  10. Push element x to the back of queue.
  11. """
  12. self.inStack.append(x)
  13. def pop(self) -> int:
  14. """
  15. Removes the element from in front of queue and returns that element.
  16. """
  17. if len(self.outStack)==0:
  18. self.in2out()
  19. return self.outStack.pop()
  20. def peek(self) -> int:
  21. """
  22. Get the front element.
  23. """
  24. if len(self.outStack)==0:
  25. self.in2out()
  26. return self.outStack[-1]
  27. def empty(self) -> bool:
  28. """
  29. Returns whether the queue is empty.
  30. """
  31. if len(self.inStack)==0 and len(self.outStack)==0:
  32. return True
  33. return False
  34. def in2out(self):
  35. while len(self.inStack)>0:
  36. self.outStack.append(self.inStack.pop())
  37. # Your MyQueue object will be instantiated and called as such:
  38. # obj = MyQueue()
  39. # obj.push(x)
  40. # param_2 = obj.pop()
  41. # param_3 = obj.peek()
  42. # param_4 = obj.empty()

JavaScript

/**
 * 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 === 0){
        this.in2out()
    }
    return this.outStack.pop()

};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (this.outStack.length === 0){
        this.in2out()
    }
    return this.outStack[this.outStack.length-1]
};

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

};
MyQueue.prototype.in2out = function() {
    while(this.inStack.length){
        this.outStack.push(this.inStack.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()
 */

复杂度分析

  • 时间复杂度:pushempty 为 O(1),poppeek 为均摊 O(1)。对于每个元素,至多入栈和出栈各两次,故均摊复杂度为 O(1)。

  • 空间复杂度:O(n)。其中 n 是操作总数。对于有 n 次 push 操作的情况,队列中会有 n 个元素,故空间复杂度为 O(n)。