0
点赞
收藏
分享

微信扫一扫

一种基于智能手机的地下停车场寻车系统

承蒙不弃 2024-01-20 阅读 10
java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846
解题思路
代码:时间复杂度O( n 2 n^2 n2).空间复杂度O(1)
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;
    }
}
举报

相关推荐

0 条评论