文章目录
☀️ 前言 ☀️
算法作为极其重要的一点,是大学生毕业找工作的核心竞争力,所以为了不落后与人,开始刷力扣算法题!
🙀 作者简介 🙀
大家好,我是布小禅,一个尽力让无情的代码变得生动有趣的IT小白,很高兴能偶认识你,关注我,每天坚持学点东西,我们以后就是大佬啦!
📢 :❤布小禅❤
📢 作者专栏:
这是我刷第 37/100 道力扣简单题
💗 一、题目描述 💗
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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
**进阶:
你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。
**
提示:提示:
1 <= x <= 9
最多调用 100 次 push、pop、peek 和 empty
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)
💁 二、题目解析 💁
思路1
声明两个栈字段
然后在构造函数里面创建两个空栈s1,s2
s1作为接收入队元素的栈,s2作为出队的栈
当实现入队操作时,判断s2是否为空,不为空将s2的值依次压入s1,再往s1里面压给定的元素
当出栈时,判断s1是否为空,不为空将s1的值依次压入s2,再让s2进行出栈操作
当判断队顶元素时,判断s1是否为空,不为空将s1的值依次压入s2,再让s2进行判断栈顶的操作
当判断是否为空时,如果s1,s2都为空,则返回true,反之返回false
🏃 三、代码 🏃
☁️ 1️⃣. python ☁️
class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.s1 = [] self.s2 = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ while len(self.s2)!=0: self.s1.append(self.s2.pop()) self.s1.append(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ while len(self.s1)!=0: self.s2.append(self.s1.pop()) return self.s2.pop() def peek(self) -> int: """ Get the front element. """ while len(self.s1)!=0: self.s2.append(self.s1.pop()) return self.s2[-1] def empty(self) -> bool: """ Returns whether the queue is empty. """ if len(self.s1)==0 and len(self.s2)==0: return True else: return False # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
❄️ 2️⃣. C# ❄️
public class MyQueue { private Stack s1; private Stack s2; /** Initialize your data structure here. */ public MyQueue() { s1 = new Stack(); s2 = new Stack(); } /** Push element x to the back of queue. */ public void Push(int x) { while (s2.Count != 0) { s1.Push(s2.Pop()); } s1.Push(x); } /** Removes the element from in front of queue and returns that element. */ public int Pop() { while (s1.Count != 0) { s2.Push(s1.Pop()); } return (int)s2.Pop(); } /** Get the front element. */ public int Peek() { while (s1.Count != 0) { s2.Push(s1.Pop()); } return (int)s2.Peek(); } /** Returns whether the queue is empty. */ public bool Empty() { if (s1.Count == 0 && s2.Count == 0) return true; else return false; } }
🌔 结语 🌔
坚持最重要,每日一题必不可少!😸
期待你的关注和督促!😛

