java数据结构与算法刷题-----LeetCode59. 螺旋矩阵 II

java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846
解题思路
  1. 初始,top行执向第一行,bottom行指向最后一行。left列指向第一列,right列指向最后一列
  2. 首先填充top行,arr[top][j], (其中left <= j <= right)。此时第一行填充完成,top下移 => top++
  3. 然后填充right列,arr[j][right], (其中top <= j <= bottom)。此时最后一列填充完成,right左移 => tright--
  4. 然后填充bottom行,arr[bottom][j], (其中right >= j >= left)。此时最后一行填充完成,bottom上移 => bottom--
  5. 然后填充left列,arr[j][left], (其中bottom >= j >= top)。此时第一列填充完成,left右移 => left++
  6. 此时完成一圈螺旋,整体进入下一层螺旋,重复上面2,3,4,5操作
代码:时间复杂度O( n 2 n^2 n2).空间复杂度O(1)
java 复制代码
class Solution {
    public int[][] generateMatrix(int n) {
        int arr[][] = new int[n][n];
        int left = 0,right = n-1;//左右边界,left表示当前顺时针圈的最左边一列,right表示最右边
        int top = 0, bottom = n-1;//上下边界,top表示当前顺时针圈的最上面一行,bottom表示最下面
        for(int i = 1;i<=n*n;){
            for(int j = left; j<= right; j++) arr[top][j] = i++;//top行从左到右填满
            top++;//上面将top行填充成功,那么top需要下移一行,准备下一次的填充
            for(int j = top; j <= bottom; j++) arr[j][right] = i++;//right列从上到下填满
            right--;//上面将right列填充成功,right左移
            for(int j = right; j >= left; j--) arr[bottom][j] = i++;//bottom行从右向左填满
            bottom--;//上面将bottom行填充成功,bottom上移
            for(int j = bottom;j>= top;   j--) arr[j][left] = i++;//left列从下到上填满
            left++;//上面将left列填充成功,left列右移
        }
        return arr;
    }
}
相关推荐
ffqws_1 分钟前
MyBatis 动态 SQL 详解:从原理到实战
java·sql·mybatis
浮尘笔记2 分钟前
在Snowy后台无需编码实现自动化生成CRUD操作流程
java·开发语言·经验分享·spring boot·后端·程序人生·mybatis
踩坑记录3 分钟前
leetcode 92. 反转链表 II 区间反转(不是整条链表反转)
leetcode·链表
-星空下无敌3 分钟前
IDEA 2025.3.1最新最全下载、安装、配置及使用教程(保姆级教程)
java·ide·intellij-idea
JAVA面经实录9176 分钟前
Spring Boot + Spring AI 一体化实战全文档
java·人工智能·spring boot·spring
cici158747 分钟前
含风光储燃的微电网能量管理系统(PSO优化)
算法
希望永不加班11 分钟前
SpringBoot 接口签名验证(AppKey/Secret)
java·spring boot·后端·spring
Das119 分钟前
图像色彩迁移技术算法及基本原理
算法
发疯幼稚鬼23 分钟前
二叉树的广度优先遍历
c语言·数据结构·算法·宽度优先
谭欣辰24 分钟前
C++ DFS 与 BFS 剪枝方法详解
c++·算法·剪枝