] [LeetCode螺旋54スパイラルマトリックスマトリックス(媒体)(JAVA)
トピック住所:https://leetcode.com/problems/spiral-matrix/
件名の説明:
m×n個の要素(m行、n列)の行列が与えられると、螺旋状の順序で行列のすべての要素を返します。
例1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
例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×nの要素のマトリックス(M行、n列)が与えられると、螺旋時計回りの順番に従って、行列のすべての要素を返します。
問題解決のアプローチ
図1に示すように、4つの部分を含む各サイクルは、右下、左上
、境界ケース特別な処理を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ミリ秒は、のJavaに提出するすべてのユーザーの100.00パーセントを破った
メモリ消費量:38.2メガバイト、Javaで提出するすべてのユーザの5.23パーセントを打ちます