遵义网站制作费用,重庆做网站 哪个好些嘛,自己可以做开奖网站吗,成全视频观看免费观看LeetCode 232. 用栈实现队列
难度#xff1a;easy\color{Green}{easy}easy 题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作#xff08;pushpushpush、poppoppop、peekpeekpeek、emptyemptyempty#xff09;#xff1a;
实现 MyQueueM…LeetCode 232. 用栈实现队列
难度easy\color{Green}{easy}easy 题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作pushpushpush、poppoppop、peekpeekpeek、emptyemptyempty
实现 MyQueueMyQueueMyQueue 类
voidpush(intx)void push(int x)voidpush(intx) 将元素 x 推到队列的末尾intpop()int pop()intpop() 从队列的开头移除并返回元素intpeek()int peek()intpeek() 返回队列开头的元素booleanempty()boolean empty()booleanempty() 如果队列为空返回 truetruetrue 否则返回 falsefalsefalse
说明
你 只能 使用标准的栈操作 —— 也就是只有 pushtotoppush to toppushtotop, peek/popfromtoppeek/pop from toppeek/popfromtop, sizesizesize, 和 isemptyis emptyisempty 操作是合法的。你所使用的语言也许不支持栈。你可以使用 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提示
1x91 x 91x9最多调用 100100100 次 pushpushpush、poppoppop、peekpeekpeek 和 emptyemptyempty假设所有操作都是有效的 例如一个空的队列不会调用 poppoppop 或者 peekpeekpeek 操作
进阶
你能否实现每个操作均摊时间复杂度为 O(1)O(1)O(1) 的队列换句话说执行 nnn 个操作的总时间复杂度为 O(n)O(n)O(n) 即使其中一个操作可能花费较长时间。 算法
(栈,队列)
我们用一个栈来存储队列中的元素另外还需要一个辅助栈用来辅助实现 pop() 和 peek() 操作。
四种操作的实现方式如下
push(x) – 直接将x插入栈顶pop() – 即需要弹出栈底元素我们先将栈底以上的所有元素插入辅助栈中然后弹出栈底元素最后再将辅助栈中的元素重新压入当前栈中peek() – 返回栈顶元素同理我们先将栈底以上的所有元素插入辅助栈中然后输出栈底元素最后再将辅助栈中的元素重新压入当前栈中恢复当前栈原状empty() – 返回当前栈是否为空
复杂度分析 时间复杂度push(x) 和 emtpy() 均只有一次操作时间复杂度是 O(1)O(1)O(1)pop() 和 peek() 涉及到 nnn 次操作所以时间复杂度是 O(n)O(n)O(n) 空间复杂度 : O(n)O(n)O(n)
C 代码
class MyQueue {
public:stackint stk1;stackint stk2;MyQueue() {}void push(int x) {stk1.push(x);}int pop() {while (stk1.size() 1) {int t stk1.top();stk1.pop();stk2.push(t);}int ans stk1.top();stk1.pop();while (stk2.size()) {stk1.push(stk2.top());stk2.pop();}return ans;}int peek() {while (stk1.size() 1) {int t stk1.top();stk1.pop();stk2.push(t);}int ans stk1.top();while (stk2.size()) {stk1.push(stk2.top());stk2.pop();}return ans;}bool empty() {if (stk1.empty()) return true;return false;}
};/*** 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();* bool param_4 obj-empty();*/