diff --git a/notes/29. 顺时针打印矩阵.md b/notes/29. 顺时针打印矩阵.md index 41c05939..e4d219dd 100644 --- a/notes/29. 顺时针打印矩阵.md +++ b/notes/29. 顺时针打印矩阵.md @@ -2,7 +2,7 @@ ## 题目链接 -[牛客网](https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) +[Leetcode](https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/) ## 题目描述 @@ -19,25 +19,39 @@

```java -public ArrayList printMatrix(int[][] matrix) { - ArrayList ret = new ArrayList<>(); - int r1 = 0, r2 = matrix.length - 1, c1 = 0, c2 = matrix[0].length - 1; +public int[] spiralArray(int[][] array) { + if (array == null || array.length == 0 || array[0].length == 0) { + return new int[0]; + } + int m = array.length, n = array[0].length; + int[] ret = new int[m * n]; + int idx = 0; + int r1 = 0, r2 = m - 1, c1 = 0, c2 = n - 1; while (r1 <= r2 && c1 <= c2) { // 上 - for (int i = c1; i <= c2; i++) - ret.add(matrix[r1][i]); + for (int i = c1; i <= c2; i++) { + ret[idx++] = array[r1][i]; + } // 右 - for (int i = r1 + 1; i <= r2; i++) - ret.add(matrix[i][c2]); - if (r1 != r2) + for (int i = r1 + 1; i <= r2; i++) { + ret[idx++] = array[i][c2]; + } + if (r1 != r2) { // 下 - for (int i = c2 - 1; i >= c1; i--) - ret.add(matrix[r2][i]); - if (c1 != c2) + for (int i = c2 - 1; i >= c1; i--) { + ret[idx++] = array[r2][i]; + } + } + if (c1 != c2) { // 左 - for (int i = r2 - 1; i > r1; i--) - ret.add(matrix[i][c1]); - r1++; r2--; c1++; c2--; + for (int i = r2 - 1; i > r1; i--) { + ret[idx++] = array[i][c1]; + } + } + r1++; + r2--; + c1++; + c2--; } return ret; }