力扣 - 剑指 Offer 29. 顺时针打印矩阵
2021-10-20 01:17
1551 查看
题目
思路1
- 其实就是按照理解题目的意思一步步从外层到内层打印出来,同时将一个外层分成四个部分分步打印
- 可以用一个变量
count
来维护当前打印的第几层 - 判断打印结束了的条件是:
count*2<column && count*2<row
- 但是要注意的是边界条件的判断,可能最里面的一层不一定要四边全部都打印出来的情况记得判断
代码
class Solution { public int[] spiralOrder(int[][] matrix) { if (matrix.length == 0) { return new int[0]; } int column = matrix[0].length; int row = matrix.length; // int[] res = new int[column * row]; // 写入到res数组的指针 int position = 0; // 代表的是第几遍循环 int count = 0; while (count*2 < column && count*2 < row) { int endColumn = column - 1 - count; int endRow = row - 1 - count; // 打印上方 // 只有这个不用判断,因为是最先打印的这个 // 如果最内圈只有一行,那么其他三个方向就都不要打印了,所以其他三个方向要判断 for (int i = count; i <= endColumn; i++) { res[position++] = matrix[count][i]; } // 打印右侧 if (count < endRow) { for (int i = count+1; i <= endRow; i++) { res[position++] = matrix[i][endColumn]; } } // 打印下方 if (count < endColumn && count < endRow) { for (int i = endColumn-1; i >= count; i--) { res[position++] = matrix[endRow][i]; } } // 打印左侧 if (count < endColumn && count < endRow) { for (int i = endRow-1; i > count; i--) { res[position++] = matrix[i][count]; } } count++; } return res; } }
复杂度分析
- 时间复杂度:\(O(M*N)\)
- 空间复杂度:\(O(1)\)
相关文章推荐
- 跟着专注于计算机视觉的AndyJ的妈妈我学算法之每日一题leetcode剑指Offer29顺时针打印矩阵
- 顺时针打印矩阵(剑指offer 面试题29)
- 【剑指Offer】面试题29:顺时针打印矩阵——JS实现
- 【剑指offer】面试题29:顺时针打印矩阵
- 牛客剑指Offer面试题29:顺时针打印矩阵
- 【剑指offer】面试题 29:顺时针打印矩阵
- 剑指offer--面试题29:顺时针打印矩阵
- 我要失业了 Day 2 剑指Offer 29. 顺时针打印矩阵
- 29_剑指offer_java_顺时针打印矩阵
- 剑指Offer面试题29:顺时针打印矩阵
- 剑指offer面试题29:顺时针打印矩阵
- [剑指Offer] 29_顺时针打印矩阵
- 【Golang】LeetCode-剑指Offer-面试题29-顺时针打印矩阵
- 【剑指offer】19顺时针打印矩阵
- 牛客网-剑指offer-19-顺时针打印矩阵
- 剑指offer---顺时针打印矩阵
- 剑指Offer--19.顺时针打印矩阵
- 剑指Offer-顺时针打印矩阵-C++-2ms-456k
- 23顺时针打印矩阵--剑指offer,java版
- 剑指offer 顺时针打印矩阵