Algorithm
本周选择的算法题是:Spiral Matrix
规则如下:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Solution
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix: return []
def get_num(r1, c1, r2, c2):
for c in range(c1, c2 + 1):
yield r1, c
for r in range(r1 + 1, r2 + 1):
yield r, c2
if r1 < r2 and c1 < c2:
for c in range(c2 - 1, c1, -1):
yield r2, c
for r in range(r2, r1, -1):
yield r, c1
ans = []
r1, r2 = 0, len(matrix) - 1
c1, c2 = 0, len(matrix[0]) - 1
while r1 <= r2 and c1 <= c2:
for r, c in get_num(r1, c1, r2, c2):
ans.append(matrix[r][c])
r1 += 1; r2 -= 1; c1 += 1; c2 -= 1
return ans
经过简化+重命名变量后和官方解法一样,这题主要考查的是 “if-else” 逻辑。
Review
Apple’s Fluid Interface Design
苹果在动画设计背后的思考。
细节决定体验
Tip
整体过了一遍 Python 的 typing 模块。
Python 的类型检查系统需要第三方工具支持,比如 pycharm、IDEs、linters 等
类型别名
设置可互换的同义词:
from typing import List
Vector = List[float]
创建新的类型
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
Callable
申明函数类型,其签名为:Callable[[Arg1Type, Arg2Type], ReturnType]
,例子为:
from typing import Callable
def feeder(get_next_item: Callable[[], str]) -> None:
pass
泛型
集合类型可以申明元素类型,支持 or
语法:
from typing import List, Dict
def foo(d: Dict[str, str]) -> None:
pass
def bar(l: List[str], l2: List[str or int]) -> None:
pass
完整的官方文档:typing — Support for type hints