目录
一、剑指 Offer 29. 顺时针打印矩阵
1.1 题求
1.2 求解
法一:模拟
# 36ms - 87.11%
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
res = []
row_min = col_min = 0 # 行、列最小值
row_max = len(matrix) - 1 # 行、列最大值
col_max = len(matrix[0]) - 1
num = (row_max+1) * (col_max+1) # 总数
while len(res) < num:
# 起点
x, y = row_min, col_min
# 如果差中间一个, 直接记录并退出循环
if len(res) == num-1:
res.append(matrix[x][y])
break
# 向右
while len(res) < num and y < col_max:
#print(x, y, res)
res.append(matrix[x][y])
y += 1
# 向下
while len(res) < num and x < row_max:
#print(x, y, res)
res.append(matrix[x][y])
x += 1
# 向左
while len(res) < num and y > col_min:
#print(x, y, res)
res.append(matrix[x][y])
y -= 1
# 向上
while len(res) < num and x > row_min:
#print(x, y, res)
res.append(matrix[x][y])
x -= 1
# 更新下一轮遍历的起点及其界限
row_min += 1
col_min += 1
row_max -= 1
col_max -= 1
return res
官方说明
# 36ms - 87.11%
class Solution:
def spiralOrder(self, matrix:[[int]]) -> [int]:
if not matrix:
return []
l, r, t, b, res = 0, len(matrix[0])-1, 0, len(matrix)-1, []
while True:
# left to right
for i in range(l, r + 1):
res.append(matrix[t][i])
t += 1
if t > b:
break
# top to bottom
for i in range(t, b + 1):
res.append(matrix[i][r])
r -= 1
if l > r:
break
# right to left
for i in range(r, l - 1, -1):
res.append(matrix[b][i])
b -= 1
if t > b:
break
# bottom to top
for i in range(b, t - 1, -1):
res.append(matrix[i][l])
l += 1
if l > r:
break
return res
1.3 解答
参考资料:
《剑指 Offer 第二版》
https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5vfh9g/
https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5vfb5v/
二、剑指 Offer 31. 栈的压入、弹出序列
2.1 题求
2.2 求解
官方说明
# 28ms - 98.02%
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = [] # 模拟栈
i = 0 # 出栈序列 popped 的指针
# 遍历压栈序列
for num in pushed:
# num 压栈
stack.append(num)
# 循环判断与出栈: 遇到 “栈顶元素 == 弹出序列的当前元素” 立即出栈
while stack and stack[-1] == popped[i]:
stack.pop()
i += 1
return not stack
2.3 解答
参考资料:
《剑指 Offer 第二版》
https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5wh1hj/
https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5wxgft/