题目描述题解(按层模拟,边界收缩法)思路代码importjava.util.ArrayList;importjava.util.List;classSolution{publicListIntegerspiralOrder(int[][]matrix){ListIntegerresultnewArrayList();// 处理边界条件空矩阵直接返回if(matrixnull||matrix.length0||matrix[0].length0){returnresult;}// 定义四个方向的边界inttop0;intbottommatrix.length-1;intleft0;intrightmatrix[0].length-1;while(true){// 1. 向右移动遍历 top 层从 left 到 rightfor(intileft;iright;i){result.add(matrix[top][i]);}top;// top 层遍历完上边界下移if(topbottom)break;// 若越界说明全部遍历完了// 2. 向下移动遍历 right 列从 top 到 bottomfor(intitop;ibottom;i){result.add(matrix[i][right]);}right--;// right 列遍历完右边界左移if(leftright)break;// 3. 向左移动遍历 bottom 层从 right 到 leftfor(intiright;ileft;i--){result.add(matrix[bottom][i]);}bottom--;// bottom 层遍历完下边界上移if(topbottom)break;// 4. 向上移动遍历 left 列从 bottom 到 topfor(intibottom;itop;i--){result.add(matrix[i][left]);}left;// left 列遍历完左边界右移if(leftright)break;}returnresult;}}复杂度分析时间复杂度O(mn)其中 m 和 n 分别是输入矩阵的行数和列数。空间复杂度O(1)。除了输出数组以外空间复杂度是常数。