Algorithm
本周选择的算法题是:Implement Queue using Stacks
规则如下:
Implement the following operations of a queue using stacks.
- push(x) – Push element x to the back of queue.
- pop() – Removes the element from in front of queue.
- peek() – Get the front element.
- empty() – Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
Notes:
- You must use only standard operations of a stack – which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
Solution
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
self.reverse_stack = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stack.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
self.peek()
return self.reverse_stack.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if not self.reverse_stack:
while self.stack:
self.reverse_stack.append(self.stack.pop())
return self.reverse_stack[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return not (self.stack or self.reverse_stack)
很简单的题目。
Review
Static Dispatch Over Dynamic Dispatch
喜欢这类文章:有观点有验证。
其中观点有:
final
- 从不被动态派发private
- 编译将对标记为该关键字的所有变量和方法执行搜索,如果找到 override 的地方将生成编译错误;如果找不到任何 override 行为,则隐式将其标记为final
- Whole-Module - 有之前的 ARTS 作业中有一篇关于它的说明:传送门
Tip
简单两步为自己的网站添加 fancybox 大图预览效果:
为所有 img 元素添加父元素
$("img").each(function () { var element = document.createElement("a"); $(element).attr("data-fancybox", "gallery"); $(element).attr("href", $(this).attr("src")); $(this).wrap(element); });
Share
无论如何,请不要只知道低头赶路,沦为一个终生的做题家。