leetcode59.螺旋矩阵II——学习笔记

题目:力扣icon-default.png?t=M1L8https://leetcode-cn.com/problems/spiral-matrix-ii/


class Solution {
    public int[][] generateMatrix(int n) {
        int target = n*n;
        int num = 1;
        int[][] map = new int[n][n];
        int left = 0;
        int right = n-1;
        int top = 0;
        int bottom = n-1;
        while(num<=target){
            //从左往右
            for(int i=left;i<=right;i++){
                map[top][i] = num;
                num++;
            }
            top++;
            //从上往下
            for(int i=top;i<=bottom;i++){
                map[i][right] = num;
                num++;
            }
            right--;
            //做右往左
            for(int i=right;i>=left;i--){
                map[bottom][i] = num;
                num++;
            }
            bottom--;
            //从下往上
            for(int i=bottom;i>=top;i--){
                map[i][left] = num;
                num++;
            }
            left++;
        }
        return map;
    }
}

 


思路:这题与leetcode54.螺旋矩阵 大同小异,leetcode54.螺旋矩阵需要做的是按照瞬时间螺旋的返回数据,而这一题需要做的是按照瞬时间给二维数组填入数据,本质上没有区别。所以我还是故技重施,抽丝剥茧般的逐行逐列的拜访数据。


1.准备阶段。target是需要放置的元素的个数(也是需要放置元素最后一位的值);num是当前放置元素的值(因为题目要求从1开始,所以默认值为1);map是最后需要返回的二维数组;left、right、top和bottom分别为左、右、上、下边界。

int target = n*n;
int num = 1;
int[][] map = new int[n][n];
int left = 0;
int right = n-1;
int top = 0;
int bottom = n-1;

2.放置元素。当num尚未达到target值一直执行循环,循环内按照“从左往右”->“从上往下”->“从右往左”->“从下往上”(即顺时间)的方向依次放入对应的元素num,每放置完一行(列)则将对应的left/right/top/bottom的值修改。

while(num<=target){
    //从左往右
    for(int i=left;i<=right;i++){
        map[top][i] = num;
        num++;
    }
    top++;
    //从上往下
    for(int i=top;i<=bottom;i++){
        map[i][right] = num;
        num++;
    }
    right--;
    //做右往左
    for(int i=right;i>=left;i--){
        map[bottom][i] = num;
        num++;
    }
    bottom--;
    //从下往上
    for(int i=bottom;i>=top;i--){
        map[i][left] = num;
        num++;
    }
    left++;
}

3.返回二维数组map。

return map;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hokachi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值