知序
返回
保存草稿
发布
H1
H2
H3
1
2
3
Excalidraw 图
AI 写作
AI 优化
目录
输入内容后显示目录
Markdown
# 24 - 螺旋矩阵 ## 题目(LeetCode 54) 给定 m×n 矩阵,按顺时针螺旋顺序返回所有元素。 ## 解法:边界收缩 ```java class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); int top = 0, bottom = matrix.length - 1; int left = 0, right = matrix[0].length - 1; while (top <= bottom && left <= right) { for (int i = left; i <= right; i++) res.add(matrix[top][i]); top++; for (int i = top; i <= bottom; i++) res.add(matrix[i][right]); right--; if (top <= bottom) for (int i = right; i >= left; i--) res.add(matrix[bottom][i]); bottom--; if (left <= right) for (int i = bottom; i >= top; i--) res.add(matrix[i][left]); left++; } return res; } } ``` ## 复杂度 - 时间 O(m×n),空间 O(1) ## 一句话总结 四个边界不断收缩,按上→右→下→左的顺序遍历。 ## 说明 螺旋矩阵遍历本质上是模拟题,边界收缩是最清晰的实现方式。另一种写法是用方向数组(右→下→左→上)加边界检查,代码量相近但不如边界收缩直观。当前解法已是最优。
预览
发布文章
添加摘要让读者更快了解文章内容
取消
确认发布
AI 写作助手
输入一个主题,AI 将为你生成一篇 Markdown 博客文章
AI 正在写作中...
取消
开始生成
AI 优化助手
描述你的修改需求,AI 将在原文基础上进行补充或微调
AI 正在优化中...
取消
开始优化
画布
从已有图里选
✕
图名
保存后生成 /images/excalidraw/<图名>.svg(只能用字母、数字、短横线、下划线、点)
取消
保存并插入