Algorithm
本周选择的算法题是:Rotate Image
规则如下:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
Solution
我实现的方案:
Runtime:28 ms,快过 91.64%。
Memory:12.8 MB,低于 100%。
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
side = len(matrix)
while side > 1:
offset = (len(matrix) - side) // 2
step, i, previous = side - 1, 0, 0
while i < side - 1:
j = i
while j < i + step * 4 + 1:
if j < side:
x, y = 0, j
elif j < side * 2 - 1:
x, y = j - side + 1, side - 1
elif j < side * 3 - 2:
x, y = side - 1, side * 3 - 3 - j
elif j < side * 4 - 3:
x, y = side * 4 - 4 - j, 0
else:
x, y = 0, i
previous, matrix[x + offset][y + offset] = matrix[x + offset][y + offset], previous
j += step
i += 1
side -= 2
而下面的解法充分利用了 python 的语言特点:
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
side = len(matrix)
for i in range(side // 2):
for j in range(side - side // 2):
matrix[i][j], matrix[~j][i], matrix[~i][~j], matrix[j][~i] = \
matrix[~j][i], matrix[~i][~j], matrix[j][~i], matrix[i][j]
Review
与上一周文章《React Higher-Order Components》很像。
相比高阶组件,Render Props 的优点是:
- 没有控制反转的问题 - 你可以控制你的组件何时、何种方式展示 UI
- 没有命名冲突 - 在冲突出现之前,你可以重命名后传递给自己的组件
Tip
很实用的的技巧,在 python 中检测多个前缀或后缀:
print("http://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk")))
#1-> True
#2-> True
Share
从 《Go语言,Docker和新技术》中总结。
一个技术能不能发展起来关键看三点:
- 有没有一个比较好的社区
- 有没有一个工业化的标准
- 有没有一个或多个杀手级的应用
其他因素:
- 学习难度
- 开发效率
- 技术支持
- 击中痛点
从个人的角度来看:
- 能参与技术发展的过程非常重要
- 抢占技术的先机能给个人建立护城河