网站备案申请模板,网页制作软件手机版,班级优化大师免费下载安装,网站搭建好了不用会不会被攻击Problem: 232. 用栈实现队列 文章目录 思路复杂度#x1f496; 朴素版#x1f496; 优化版 思路
#x1f468;#x1f3eb; 路飞题解
复杂度
时间复杂度: 添加时间复杂度, 示例#xff1a; O ( n ) O(n) O(n) 空间复杂度: 添加空间复杂度, 示例#xff1a; O ( … Problem: 232. 用栈实现队列 文章目录 思路复杂度 朴素版 优化版 思路
路飞题解
复杂度
时间复杂度: 添加时间复杂度, 示例 O ( n ) O(n) O(n) 空间复杂度: 添加空间复杂度, 示例 O ( n ) O(n) O(n) 朴素版
class MyQueue {StackInteger s1;StackInteger s2;public MyQueue() {s1 new Stack();s2 new Stack();}public void push(int x) {while(!s1.isEmpty()){s2.push(s1.pop());}s2.push(x);while(!s2.isEmpty()){s1.push(s2.pop());}}public int pop() {return s1.pop();}public int peek() {return s1.peek();}public boolean empty() {return s1.isEmpty();}
}/*** Your MyQueue object will be instantiated and called as such:* MyQueue obj new MyQueue();* obj.push(x);* int param_2 obj.pop();* int param_3 obj.peek();* boolean param_4 obj.empty();*/优化版
class MyQueue {private StackInteger A;private StackInteger B;public MyQueue() {A new Stack();B new Stack();}public void push(int x) {A.push(x);}public int pop() {int peek peek();B.pop();return peek;}public int peek() {if (!B.isEmpty()) return B.peek();if (A.isEmpty()) return -1;while (!A.isEmpty()){B.push(A.pop());}return B.peek();}public boolean empty() {return A.isEmpty() B.isEmpty();}
}