59. 螺旋矩阵II

模拟

class Solution {
    public int[][] generateMatrix(int n) {

        /**
         * 定义上下左右边界,每次循环一圈后都要缩小边界
         * 从1开始赋值
         */
        int[][] arr = new int[n][n];
        int top = 0;
        int bottom = n - 1;
        int left = 0;
        int right = n - 1;

        int res = 1;

        while (res <= n * n) {

            /**
             * 第一行
             */
            for (int i = left; i <= right; i++) {
                arr[top][i] = res++;
            }

            /**
             * 缩小边界
             */
            top++;

            for (int i = top; i <= bottom; i++) {
                arr[i][right] = res++;
            }

            right--;

            for (int i = right; i>= left; i--) {
                arr[bottom][i] = res++;
            }

            bottom--;

            for (int i = bottom; i >= top; i--) {
                arr[i][left] = res++;
            }

            left++;
        }

        return arr;
    }
}

/**
 * 时间复杂度 O(n^2)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/spiral-matrix-ii/

posted @   振袖秋枫问红叶  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示