题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
限制:
0 <= matrix.length <= 1000 <= matrix[i].length <= 100
解题思路
将矩阵看成若干层,首先打印最外层的元素,其次打印次外层的元素,直到打印最内层的元素。对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于(top,left),右下角位于(bottom,right),按照如下顺序遍历当前层的元素:
1)从左到右遍历上侧元素,依次为 (top,left) 到 (top,right)。
2)如果 top<bottom,则从上到下遍历右侧元素,依次为 (top+1,right) 到 (bottom,right)。
3)如果 top<bottom 且 left<right,则从右到左遍历下侧元素,依次为 (bottom,right−1) 到 (bottom,left),
4)如果 top<bottom-1 且 left<right,则从下到上遍历左侧元素,依次为 (bottom-1,left) 到 (top+1,left)。
遍历完当前层的元素之后,将 left 和 top 分别增加 1,将right 和 bottom 分别减少 1,进入下一层继续遍历,直到遍历完所有元素为止。
复杂度分析:
时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。
空间复杂度:O(1)。除了输出数组以外,空间复杂度是常数。
代码
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return new int[0];
}
int m = matrix.length;
int n = matrix[0].length;
int[] res = new int[m*n];
int top = 0, left = 0;
int bottom = m-1, right = n-1;
int k=0;
while(top <= bottom && left <= right){
// 从左到右遍历上侧元素
for(int j=left; j<=right; j++){
res[k++] = matrix[top][j];
}
// 从上到下遍历右侧元素
if(top<bottom){
for(int i=top+1; i<=bottom; i++){
res[k++] = matrix[i][right];
}
}
// 从右到左遍历下侧元素
if(top<bottom && left<right){
for(int j=right-1; j>=left; j--){
res[k++] = matrix[bottom][j];
}
}
// 从下到上遍历左侧元素
if(top<bottom-1 && left<right){
for(int i=bottom-1; i>=top+1; i--){
res[k++] = matrix[i][left];
}
}
// 进入下一层
top++;
left++;
bottom--;
right--;
}
return res;
}
}
493


顺时针打印矩阵&spm=1001.2101.3001.11974&articleId=106578336&d=1&t=3&u=af822dbc09f843759cfb6e04a1f5fcea)

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



