0
点赞
收藏
分享

微信扫一扫

Leetcode 题解-59题


  • 思路主要参考了代码随想录,自己复现了一遍

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new  int[n][n];

        int startx = 0;
        int starty = 0;
        int mid = n / 2;
        int loop = n / 2;
        int count = 1;
        int off = 1;
        int i, j;

        while (loop > 0) {
            i = startx;
            j = starty;

            for (; j < starty + n - off; j++) { //从左往右,填充(starty+n-off)次 
                res[startx][j] = count++;
            }

            for (; i < startx + n - off; i++) { //从上往下,填充(startx+n-x)次
                res[i][j] = count++ ;
            }

            for (; j > starty; j--) { //从右往左,填充(j-starty)次
                res[i][j] = count++;
            }

            for (; i > startx; i--) { //从下往上,填充(i-startx)次
                res[i][j] = count++;
            }

            loop --; //圈数减一
            startx ++;
            starty ++;
            off += 2; //每填充完一圈,单列填充减少2次!
        }

        if (n % 2 == 1) { //奇数额外填充数字
            res [mid][mid] = count;
        }

        return res;   
    }
}
举报

相关推荐

0 条评论