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;
    }
}
相关推荐
时间静止不是简史几秒前
当MyBatis-Plus的like遇上SQL通配符:下划线翻车记
java·sql·mybatis
两年半的个人练习生^_^4 分钟前
每日一学:设计模式之建造者模式
java·开发语言·设计模式
纤纡.4 分钟前
基于 TextRNN 的微博情绪分类系统实现与解析
人工智能·算法·分类·数据挖掘
hehelm4 分钟前
string的模拟实现
数据结构·算法
我登哥MVP5 分钟前
【SpringMVC笔记】 - 6 - RESTFul编程风格
java·spring boot·spring·servlet·tomcat·maven·restful
白羊by6 分钟前
逻辑回归与Softmax的区别
算法·机器学习·逻辑回归
Tisfy9 分钟前
LeetCode 3761.镜像对之间最小绝对距离:哈希表(维护左,枚举右)
算法·leetcode·散列表·题解
小鱼~~9 分钟前
逻辑回归简介
算法·机器学习·逻辑回归
yhole10 分钟前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
zjjsctcdl10 分钟前
SpringBoot3.3.0集成Knife4j4.5.0实战
java