Algorithm
本周选择的算法题是:Min Stack。
规则
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack
class:
MinStack()
initializes the stack object.void push(val)
pushes the elementval
onto the stack.void pop()
removes the element on the top of the stack.int top()
gets the top element of the stack.int getMin()
retrieves the minimum element in the stack.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
-231 <= val <= 231 - 1
- Methods
pop
,top
andgetMin
operations will always be called on non-empty stacks. - At most
3 * 104
calls will be made topush
,pop
,top
, andgetMin
.
Solution
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
import math
self.stack = []
self.min_stack = [math.inf]
def push(self, val: int) -> None:
self.stack.append(val)
self.min_stack.append(min(val, self.min_stack[-1]))
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
Review
Swift 5: Why Is Protocol-Oriented Programming Essential
一篇介绍什么是面向协议编程的文章,作者用清晰而易懂的方法讲解了如何将一个 God Class 变得更干净,对大型、复杂工程非常有帮助。
在实际开发过程中,特别容易形成多种角色混在一起的 God Class,比如这篇 抖音 iOS 最复杂功能的重构之路 – 播放器交互区重构实践 文章中提到的,一个 VC 就有 1.8 万行代码,重构的难度、风险可想而知,但是不重构又有维护性差、可读性差、扩展性差等问题,业务交付越来越困难,重构只是时间早晚而已。
面向协议的编程方法在面对复杂场景时还是有独特优势的。
Tip
发现了一个 macOS 下识别截屏文案的应用:TextSniper,难得的是对中文的支持也很好。