给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
用for循环
if(matrix == null) return null;
List<Integer> res = new ArrayList<>();
if (matrix.length == 0) return res;
int top = 0;
int bottom = matrix.length - 1; // matrix.length一共有多少行,如果一共有4行,那么bottom就是3
int left = 0;
int right = matrix[0].length - 1; //拿出第0行行看它有多少列
while (top <= bottom && left <= right) {
// left top - > right top
for (int i = left; i <= right;i++) {
res.add(matrix[top][i]);
}
top++;
if (top > bottom)break;
// top right = bottom right
for (int i = top; i <= bottom; i++) {
res.add(matrix[i][right]);
}
right--;
if (right < left)break;;
// bottom right => bottom left
for (int i = right; i >=left ; i--) {
res.add(matrix[bottom][i]);
}
bottom--;
if (top > bottom)break;
// bottom left => top left
for (int i = bottom; i >= top; i--){
res.add(matrix[i][left]);
}
left++;
}
return res;
用while
public static List<Integer> spiralOrderF(int[][] matrix) {
if(matrix == null) return null;
List<Integer> res = new ArrayList<>();
if (matrix.length == 0) return res;
int top = 0;
int bottom = matrix.length - 1; // matrix.length一共有多少行,如果一共有4行,那么bottom就是3
int left = 0;
int right = matrix[0].length - 1; //拿出第0行行看它有多少列
while (top <= bottom && left <= right) {
// left top - > right top
int i = left;
while (i <= right) {
res.add(matrix[top][i++]);
}
top++;
if (top > bottom)break;
// top right = bottom right
int j = top;
while (j <= bottom) {
res.add(matrix[j++][right]);
}
right--;
if (right < left)break;;
// bottom right => bottom left
int k = right;
while (left <= k) {
res.add(matrix[bottom][k--]);
}
bottom--;
int f = bottom;
if (top > bottom)break;
// bottom left => top left
while (top <= f) {
res.add(matrix[f--][left]);
}
left++;
}
return res;
}
下面错误的代码 以此为戒
错误的代码,没有用int i = left,然后再操作(int i = left 这个i只是拷贝了Left这个值,所以改变i的值并没有改变left原来的位置), 而是直接操作了left,以至于后面的根本条件不成立
//
public static List<Integer> spiralOrder(int[][] matrix) {
if(matrix == null) return null;
List<Integer> res = new ArrayList<>();
if (matrix.length == 0) return res;
int top = 0;
int bottom = matrix.length - 1; // matrix.length一共有多少行,如果一共有4行,那么bottom就是3
int left = 0;
int right = matrix[0].length - 1; //拿出第0行行看它有多少列
while (top <= bottom && left <= right) {
// left top - > right top
while (left <= right) {
res.add(matrix[top][left++]); // 这里直接操作left++以至于后面left <= right的条件不成立
}
left--;
top++;
if (top > bottom)break;
// top right = bottom right
while (top <= bottom) {
res.add(matrix[top++][right]);
}
top--;
right--;
if (right < left)break;;
// bottom right => bottom left
while (left <= right) {
res.add(matrix[bottom][right--]);
}
right++;
bottom--;
if (top > bottom)break;
// bottom left => top left
while (top <= bottom) {
res.add(matrix[bottom--][left]);
}
bottom++;
left++;
}
return res;
}