【LeetCode】 54. Spiral Matrix 螺旋矩阵(Medium)(JAVA)
题目地址: https://leetcode.com/problems/spiral-matrix/
题目描述:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[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]
题目大意
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
解题方法
1、每次一循环包括四部分,右下左上
2、特殊处理边界情况
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix.length == 0 || matrix[0].length == 0) return res;
int len = Math.min(matrix.length, matrix[0].length);
for (int i = 0; i <= (len % 2 == 0 ? len / 2 - 1 : len / 2); i++) {
for (int j = i; j < matrix[0].length - i; j++) {
res.add(matrix[i][j]);
}
for (int j = i + 1; j < matrix.length - i; j++) {
res.add(matrix[j][matrix[0].length - 1 - i]);
}
for (int j = matrix[0].length - 1 - i - 1; j >= i && i < len / 2; j--) {
res.add(matrix[matrix.length - 1 - i][j]);
}
for (int j = matrix.length - 1 - i - 1; j > i && i < len / 2; j--) {
res.add(matrix[j][i]);
}
}
return res;
}
}
执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 38.2 MB, 在所有 Java 提交中击败了 5.23% 的用户