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(双端队列)来模拟一个栈,只要是标准的栈操作即可。

示例 1:

输入:
["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 操作)

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

解题思路

解题思路

这道题要求用两个栈来实现队列的功能。栈是后进先出(LIFO),而队列是先进先出(FIFO),关键在于如何利用两个栈的特性来模拟队列的行为。

核心思路:双栈法

使用两个栈:

  • 输入栈(inStack):用于接收新元素
  • 输出栈(outStack):用于输出元素

操作原理:

  1. push操作:直接将元素压入输入栈
  2. pop/peek操作
    • 如果输出栈不为空,直接从输出栈弹出/查看
    • 如果输出栈为空,将输入栈的所有元素依次弹出并压入输出栈,然后从输出栈操作

这样设计的巧妙之处在于:当元素从输入栈转移到输出栈时,顺序会发生逆转,正好符合队列先进先出的特性。

均摊复杂度分析: 虽然单次pop操作在最坏情况下需要O(n)时间(转移所有元素),但每个元素最多被转移一次,所以n次操作的总时间复杂度为O(n),均摊时间复杂度为O(1)。

代码实现

class MyQueue {
private:
    stack<int> inStack;
    stack<int> outStack;
    
    void transferIfNeeded() {
        if (outStack.empty()) {
            while (!inStack.empty()) {
                outStack.push(inStack.top());
                inStack.pop();
            }
        }
    }
    
public:
    MyQueue() {
        
    }
    
    void push(int x) {
        inStack.push(x);
    }
    
    int pop() {
        transferIfNeeded();
        int result = outStack.top();
        outStack.pop();
        return result;
    }
    
    int peek() {
        transferIfNeeded();
        return outStack.top();
    }
    
    bool empty() {
        return inStack.empty() && outStack.empty();
    }
};
class MyQueue:

    def __init__(self):
        self.in_stack = []
        self.out_stack = []
    
    def _transfer_if_needed(self):
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())

    def push(self, x: int) -> None:
        self.in_stack.append(x)

    def pop(self) -> int:
        self._transfer_if_needed()
        return self.out_stack.pop()

    def peek(self) -> int:
        self._transfer_if_needed()
        return self.out_stack[-1]

    def empty(self) -> bool:
        return not self.in_stack and not self.out_stack
public class MyQueue {
    private Stack<int> inStack;
    private Stack<int> outStack;

    public MyQueue() {
        inStack = new Stack<int>();
        outStack = new Stack<int>();
    }
    
    private void TransferIfNeeded() {
        if (outStack.Count == 0) {
            while (inStack.Count > 0) {
                outStack.Push(inStack.Pop());
            }
        }
    }
    
    public void Push(int x) {
        inStack.Push(x);
    }
    
    public int Pop() {
        TransferIfNeeded();
        return outStack.Pop();
    }
    
    public int Peek() {
        TransferIfNeeded();
        return outStack.Peek();
    }
    
    public bool Empty() {
        return inStack.Count == 0 && outStack.Count == 0;
    }
}
var MyQueue = function() {
    this.stack1 = [];
    this.stack2 = [];
};

MyQueue.prototype.push = function(x) {
    this.stack1.push(x);
};

MyQueue.prototype.pop = function() {
    this.peek();
    return this.stack2.pop();
};

MyQueue.prototype.peek = function() {
    if (this.stack2.length === 0) {
        while (this.stack1.length > 0) {
            this.stack2.push(this.stack1.pop());
        }
    }
    return this.stack2[this.stack2.length - 1];
};

MyQueue.prototype.empty = function() {
    return this.stack1.length === 0 && this.stack2.length === 0;
};

复杂度分析

操作时间复杂度空间复杂度
pushO(1)O(1)
pop均摊 O(1)O(1)
peek均摊 O(1)O(1)
emptyO(1)O(1)
整体空间复杂度-O(n)

说明: pop 和 peek 操作在最坏情况下需要 O(n) 时间(当需要转移所有元素时),但由于每个元素最多被转移一次,所以均摊时间复杂度为 O(1)。

相关题目