import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param matrix int整型二维数组 * @return int整型一维数组 */ public int[] printMatrixInSpiralOrder (int[][] matrix) { // 左边界 int left = 0; // 右边界 int right = matrix[0].length - 1; // 上边界 int top = 0; // 下边界 int bottom = matrix.length - 1; ArrayList<Integer> arrayList = new ArrayList<>(); while (left <= right && top <= bottom) { // 遍历第一行 1 2 3 for (int i = left; i <= right ; i++) { arrayList.add(matrix[top][i]); } top++; // 遍历最右边一列,此时top已经++,所以刚好添加的是6,9 for (int i = top; i <= bottom; i++) { arrayList.add(matrix[i][right]); } right--; // 遍历最下边一行,此时right--,刚好添加7,8 for (int i = right; i >= left && top <= bottom ; i--) { arrayList.add(matrix[bottom][i]); } bottom--; // 遍历最左边一列,此时bottom--,刚好添加4 for (int i = bottom; i >= top && left <= right ; i--) { arrayList.add(matrix[i][left]); } left++; // 此时 left = 1,top = 1,其实就是将循环的起始点变成了1,1的位置,下一次会添加5,然后跳出循环,因为top>bottom } int [] result = new int [arrayList.size()]; for (int i = 0; i < arrayList.size(); i++) { result[i] = arrayList.get(i); } return result; } }
本题知识点分析:
1.本题就是螺旋矩阵I,顺时针打印矩阵
2.数学模拟为主
3.集合存取
4.集合转数组
本题解题思路分析:
1.分别设置上下左右四个边界
2.循环条件是左边界小于等于右边界并且上边界小于等于下边界
3.注意点:如果测试用例只有一行,那么需要保证i >= left && top <= bottom 和 i >= top && left <= right,因为这个时候right和top已经发生了变化,可能已经不满足循环条件,因此在for循环中加入
4.注释写的很详细,就是数学模拟,想明白了以后就可以自己写出来,另外螺旋矩阵二其实是同理的,无非是创建一个变量count,然后也是顺时针遍历,count++,然后把count顺序赋值给当前遍历的矩阵的节点
本题使用编程语言: Java
如果你觉得本篇文章对你有帮助的话,可以点个赞,支持一下,感谢~