59. Spiral Matrix II

这道题和另一道题目54. Spiral Matrix,很相似,我觉得会了那道题,这题是很简单的,下面是那题的博客链接

https://blog.csdn.net/dreamjay1997/article/details/87437861

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

题解:先建立一个轮廓,然后按题意一圈一圈填充值就行了,因为行和列都为n,所以结果是个矩形,这降低了难度

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
    let number = []
    let total = 1
    let top = 0, bottom = n, right = n
    for(let i = 0; i < n; i ++) number[i] = []
    while(total < n * n) {
        for(let i = top; i < right - 1; i ++, total ++){
            number[top][i] = total
        }
        for(let i = top; i < bottom - 1; i ++, total ++) {
            number[i][right - 1] = total
        }
        for(let i = right - 1;  i > top; i --, total ++) {
            number[bottom - 1][i] = total
        }
        for(let i = bottom - 1; i > top; i --, total ++) {
            number[i][top] = total 
        }
        top ++
        bottom --
        right -- 
    }
    if(n % 2) {
        let h = parseInt(n / 2)
        number[h][h] = n * n
    }
    return number
};

 

Runtime: 72 ms, faster than 28.65% of JavaScript online submissions for Spiral Matrix II.

Memory Usage: 33.8 MB, less than 100.00% of JavaScript online submissions for Spiral Matrix II.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值