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/

上一篇:【贪心优化DP】B. 小 A 的卡牌游戏


下一篇:Python中的切片拷贝和可变参数传参