题解 | 螺旋矩阵
螺旋矩阵
https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix int整型二维数组
* @return int整型ArrayList
*/
public ArrayList<Integer> spiralOrder (int[][] matrix) {
// write code here
if (matrix.length == 0) return new ArrayList<>();
ArrayList<Integer> res = new ArrayList<>();
// 定义矩形的四个边,想象成一条直线,不要想象成某个点
// top/bottom就是行级别的,left和right就是列级别的
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (left <= right && top <= bottom) {
// 从左到右
for (int i = left; i <= right; i++) {
res.add(matrix[top][i]);
}
top++;
// 从上到下
for (int i = top; i <= bottom; i++) {
res.add(matrix[i][right]);
}
right--;
// 若存在合理下边界,则遍历下边界,因为前面top/bottom中的top值有变化
if (top <= bottom) {
// 从左到右
for (int i = right; i >= left; i--) {
res.add(matrix[bottom][i]);
}
bottom--;
}
// 若存在合理左边界,则遍历左边界,因为前面left/right中的right值有变化
if (left <= right) {
// 从下到上
for (int i = bottom; i >= top; i--) {
res.add(matrix[i][left]);
}
left++;
}
}
return res;
}
}

顺丰集团工作强度 335人发布