ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Kimi LeetCode 54. 螺旋矩阵 Python3实现

Kimi    LeetCode 54. 螺旋矩阵 Python3实现 LeetCode 54. 螺旋矩阵经典边界收缩模拟题。思路维护四个边界按顺时针方向逐层遍历top → ┌────────┐ │ 1 2 3 │ → right left ↓ │ 4 5 6 │ ↑ │ 7 8 9 │ └────────┘ bottom从左到右遍历top行然后top从上到下遍历right列然后right--从右到左遍历bottom行然后bottom--从下到上遍历left列然后left边界交叉时结束。Python3 实现classSolution:defspiralOrder(self,matrix:List[List[int]])-List[int]:ifnotmatrixornotmatrix[0]:return[]m,nlen(matrix),len(matrix[0])top,bottom0,m-1left,right0,n-1result[]whiletopbottomandleftright:# 1. 从左到右遍历 top 行forcolinrange(left,right1):result.append(matrix[top][col])top1# 2. 从上到下遍历 right 列forrowinrange(top,bottom1):result.append(matrix[row][right])right-1# 3. 从右到左遍历 bottom 行需检查是否还有行iftopbottom:forcolinrange(right,left-1,-1):result.append(matrix[bottom][col])bottom-1# 4. 从下到上遍历 left 列需检查是否还有列ifleftright:forrowinrange(bottom,top-1,-1):result.append(matrix[row][left])left1returnresult复杂度时间复杂度O(m × n)每个元素访问一次空间复杂度O(1)不计输出数组关键点步骤 3 和 4 需要加if判断防止在单行或单列矩阵时重复遍历每遍历完一条边立即收缩对应边界循环条件top bottom and left right确保不越界
返回列表