中等
给你一个 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
思路:
模拟: 第一个周期:行的第一行,列的倒数第一列,行的倒数第一行,列的第一列;第二个周期:行的第二行,列的倒数第二列,行的倒数第二行,列的第二列.....
class Solution {
public List<Integer> spiralOrder(int[][] matrix){
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
// 从左到右遍历顶部行
for (int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++;
// 从上到下遍历右侧列
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--;
if (top <= bottom) {
// 从右到左遍历底部行
for (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
bottom--;
}
if (left <= right) {
// 从下到上遍历左侧列
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++;
}
}
return result;
}
}
521

被折叠的 条评论
为什么被折叠?



