Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return
[1,2,3,6,9,8,7,4,5]
.
就是一层一层的处理矩阵, 实现中要注意两个细节,一个是因为题目中没有说明矩阵是不是方阵,因此要先判断一下行数和列数来确定螺旋的层数。另一个是走一次是走两行两列, 但是如果遇(行和列中间最小的是)单数的, 还要再判定一下然后继续走完.
时间复杂度O(m*n)空间O(1)public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return res; } int row = matrix.length; int col = matrix[0].length; int min = Math.min(row, col); int mid = min / 2; for (int i = 0; i < mid; i++) { for (int j = i; j < col - i - 1; j++) { res.add(matrix[i][j]); } for (int j = i; j < row - i - 1; j ++) { res.add(matrix[j][col - i - 1]); } for (int j = col - i - 1; j > i; j--) { res.add(matrix[row - i - 1][j]); } for (int j = row - i -1; j > i; j--) { res.add(matrix[j][i]); } } if (min % 2 == 1) { if (row < col) { for (int j = mid; j < col - mid; j++) { res.add(matrix[mid][j]); } } else { for (int j = mid; j < row - mid; j++) { res.add(matrix[j][mid]); } } } return res; } }
没有评论:
发表评论