Given an m x n
matrix
, return all elements of the matrix
in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
螺旋矩阵。
题意是给一个二维数组,请你螺旋遍历input,输出一个一维数组记录螺旋遍历的结果。
这个题我没有什么比较巧妙的思路,只能照着遍历的方式去实现了代码,按照右 - 下 - 左 - 上的顺序去遍历。这个题做的时候需要用几个变量去记录二维数组坐标的边界,同时记得当每一行/列遍历完了之后,边界值需要减1因为遍历的时候每一圈的size都在减小。
时间O(mn)
空间O(n) - 输出是一个一维数组
JavaScript实现
1 /** 2 * @param {number[][]} matrix 3 * @return {number[]} 4 */ 5 var spiralOrder = function (matrix) { 6 let res = []; 7 if (matrix.length === 0) { 8 return res; 9 } 10 let rowBegin = 0; 11 let rowEnd = matrix.length - 1; 12 let colBegin = 0; 13 let colEnd = matrix[0].length - 1; 14 15 while (colBegin <= colEnd && rowBegin <= rowEnd) { 16 // right 17 for (var i = colBegin; i <= colEnd; i++) { 18 res.push(matrix[rowBegin][i]); 19 } 20 rowBegin++; 21 22 // down 23 for (var i = rowBegin; i <= rowEnd; i++) { 24 res.push(matrix[i][colEnd]); 25 } 26 colEnd--; 27 28 // left 29 if (rowBegin <= rowEnd) { 30 for (var i = colEnd; i >= colBegin; i--) { 31 res.push(matrix[rowEnd][i]); 32 } 33 } 34 rowEnd--; 35 36 // up 37 if (colBegin <= colEnd) { 38 for (var i = rowEnd; i >= rowBegin; i--) { 39 res.push(matrix[i][colBegin]); 40 } 41 } 42 colBegin++; 43 } 44 return res; 45 };
Java实现
1 class Solution { 2 public List<Integer> spiralOrder(int[][] matrix) { 3 List<Integer> res = new ArrayList<>(); 4 // corner case 5 if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) { 6 return res; 7 } 8 9 // normal case 10 int rowBegin = 0; 11 int rowEnd = matrix.length - 1; 12 int colBegin = 0; 13 int colEnd = matrix[0].length - 1; 14 while (rowBegin <= rowEnd && colBegin <= colEnd) { 15 // right 16 for (int i = colBegin; i <= colEnd; i++) { 17 res.add(matrix[rowBegin][i]); 18 } 19 rowBegin++; 20 21 // down 22 for (int i = rowBegin; i <= rowEnd; i++) { 23 res.add(matrix[i][colEnd]); 24 } 25 colEnd--; 26 27 // left 28 if (rowBegin <= rowEnd) { 29 for (int i = colEnd; i >= colBegin; i--) { 30 res.add(matrix[rowEnd][i]); 31 } 32 } 33 rowEnd--; 34 35 // up 36 if (colBegin <= colEnd) { 37 for (int i = rowEnd; i >= rowBegin; i--) { 38 res.add(matrix[i][colBegin]); 39 } 40 } 41 colBegin++; 42 } 43 return res; 44 } 45 }