知序
返回
保存草稿
发布
H1
H2
H3
1
2
3
Excalidraw 图
AI 写作
AI 优化
目录
输入内容后显示目录
Markdown
# 34 - 用栈实现队列 ## 题目(LeetCode 232) 用两个栈实现队列的 push、pop、peek、empty 操作。 ## 解法:双栈 ```java class MyQueue { Deque<Integer> in, out; public MyQueue() { in = new ArrayDeque<>(); out = new ArrayDeque<>(); } public void push(int x) { in.push(x); } public int pop() { if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop()); return out.pop(); } public int peek() { if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop()); return out.peek(); } public boolean empty() { return in.isEmpty() && out.isEmpty(); } } ``` ## 复杂度 - 均摊 O(1) ## 一句话总结 in 栈负责入队,out 栈负责出队,out 空了就把 in 倒过来。 ## 说明 用两个栈实现队列是经典设计题,双栈方案(in 栈 + out 栈)是唯一能做到均摊 O(1) 的方法。每个元素最多被移动一次(从 in 到 out),所以均摊时间是 O(1)。当前解法已是最优。
预览
发布文章
添加摘要让读者更快了解文章内容
取消
确认发布
AI 写作助手
输入一个主题,AI 将为你生成一篇 Markdown 博客文章
AI 正在写作中...
取消
开始生成
AI 优化助手
描述你的修改需求,AI 将在原文基础上进行补充或微调
AI 正在优化中...
取消
开始优化
画布
从已有图里选
✕
图名
保存后生成 /images/excalidraw/<图名>.svg(只能用字母、数字、短横线、下划线、点)
取消
保存并插入