[LeetCode 59] 螺旋矩阵 II

题目描述

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]## 题目分析

这道题和螺旋矩阵一样,就是从上右下左的顺序慢慢打印数字,有几个就打印n^2个数字就完事啦

源码

class Solution {
public int[][] generateMatrix(int n) {
    int[][] arr = new int[n][n];
    int c = 1, j = 0;
    while (c <= n * n) {
    
        for (int i = j; i < n - j; i++)
            arr[j][i] = c++;
        for (int i = j + 1; i < n - j; i++)
            arr[i][n - j - 1] = c++;
        for (int i = n - j - 2; i >= j; i--)
            arr[n - j - 1][i] = c++;
        for (int i = n -j - 2; i > j; i--)
            arr[i][j] = c++;

        j++;
    }

    return arr;
}

}

改进

这道题当然也有递归的做法,但是复杂度又点高了,个人相比之下还是喜欢循环,简洁易懂。

改进代码

 class Solution {
 public int[][] generateMatrix(int n) {
    int[][] ans=new int[n][n];
    writeCircle(0,n-1,0,n-1,1,ans);
    return ans;
}

public void writeCircle(int startCol,int endCol,int startRow,int endRow,int st,int[][] ans){
    if(startCol<endCol&&startRow<endRow){
    //最上
        for(int j=startCol;j<=endCol;j++){
            ans[startRow][j]=st++;
        }
        //最右
        for(int i =startRow+1;i<=endRow;i++){
            ans[i][endCol]=st++;
        }
        //最下
        for(int j=endCol-1;j>=startCol;j--){
            ans[endRow][j]=st++;
        }
        最左
        for(int i=endRow-1;i>=startRow+1;i--){
            ans[i][startCol]=st++;
        }
        //终止
    }else if(startCol<endCol&&startRow==endRow){
        for(int j=startCol;j<=endCol;j++){
            ans[startRow][j]=st++;
        }
    }else if(startCol==endCol&&startRow<endRow){
        for(int i=startRow;i<=endRow;i++){
            ans[i][startCol]=st++;
        }
    }else if(startRow==endRow&startCol==endCol){
        ans[startRow][startCol]=st++;
    }else
        return;
    writeCircle(startCol+1,endCol-1,startRow+1,endRow-1,st,ans);
}

}

分析

第一个时间复杂度为O(n)
第二个时间复杂度为O(n*m)

难点

这道题还是比较中规中矩的,个人还是选择循环吧,比较容易理解,没有什么难点

小结

最主要的还是把各个点的索引找到,然后慢慢填数进去就行

[1]https://leetcode-cn.com/problems/spiral-matrix-ii/submissions/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值