关注
文末的名片达文汐
,回复关键词“力扣源码”,即可获取完整源码!!详见:源码和核心代码的区别
题目详情
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
解题思路
核心思想:模拟螺旋遍历的过程,通过维护四个边界(上、下、左、右)逐步缩小遍历范围。每次循环遍历一层外圈,然后向内收缩边界,直至遍历完所有元素。
具体步骤:
-
初始化边界:
top
:上边界(初始为0)bottom
:下边界(初始为行数-1)left
:左边界(初始为0)right
:右边界(初始为列数-1)
-
顺时针遍历:
- 从左到右:遍历上边界行(
top
),从left
到right
,完成后上边界下移(top++
)。 - 从上到下:遍历右边界列(
right
),从top
到bottom
,完成后右边界左移(right--
)。 - 从右到左:遍历下边界行(
bottom
),从right
到left
(需确保仍有未遍历的行,即top <= bottom
),完成后下边界上移(bottom--
)。 - 从下到上:遍历左边界列(
left
),从bottom
到top
(需确保仍有未遍历的列,即left <= right
),完成后左边界右移(left++
)。
- 从左到右:遍历上边界行(
-
终止条件:当所有边界收缩后仍满足
top <= bottom
且left <= right
时继续循环。
亮点:
- 时间复杂度:O(m×n),每个元素仅访问一次。
- 空间复杂度:O(1)(除结果列表外无额外空间开销),结果列表为必需空间。
代码实现(Java版)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0) return result;
int m = matrix.length;
int n = matrix[0].length;
int total = m * n;
// 预分配结果列表容量,避免扩容开销
result = new ArrayList<>(total);
int top = 0, bottom = m - 1;
int left = 0, right = n - 1;
while (result.size() < total) {
// 从左到右遍历上边界
for (int i = left; i <= right && result.size() < total; i++) {
result.add(matrix[top][i]);
}
top++; // 上边界下移
// 从上到下遍历右边界
for (int i = top; i <= bottom && result.size() < total; i++) {
result.add(matrix[i][right]);
}
right--; // 右边界左移
// 从右到左遍历下边界
for (int i = right; i >= left && result.size() < total; i--) {
result.add(matrix[bottom][i]);
}
bottom--; // 下边界上移
// 从下到上遍历左边界
for (int i = bottom; i >= top && result.size() < total; i--) {
result.add(matrix[i][left]);
}
left++; // 左边界右移
}
return result;
}
}
代码说明
- 边界初始化:
top
、bottom
、left
、right
分别标记当前未遍历矩阵的边界位置。
- 循环条件:
- 使用
result.size() < total
确保所有元素被遍历,避免边界收缩后遗漏元素。
- 使用
- 四个遍历方向:
- 每次循环按顺序处理四个边界,并在每次遍历后收缩对应边界。
- 提前终止:
- 每个方向的循环均检查
result.size() < total
,确保添加元素后立即终止,避免重复访问。
- 每个方向的循环均检查
- 性能优化:
- 预分配结果列表容量(
total = m * n
),避免动态扩容带来的额外开销。 - 每个元素仅访问一次,时间复杂度最优(O(mn))。
- 预分配结果列表容量(