59. 螺旋矩阵 II——矩阵、数组

本文介绍了一种名为Solution的类,其generateMatrix方法通过递归生成一个n阶矩阵,展示了如何利用循环和变量控制来构造数独似的矩阵。该算法运行效率超过100%,内存使用也优于49.61%的cpp代码。
摘要由CSDN通过智能技术生成
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
         vector<vector<int>> vec_vec_int(n, vector<int>(n));
        int num = 1;
        int n2 = n * n;
        int left = 0,right = n - 1, top = 0, bottom = n - 1;
        while(num <= n2){
            for(int j = left; j <= right; j++){
                vec_vec_int[top][j] = num++;
            }
            top++;
            for(int j = top; j <= bottom; j++){
                vec_vec_int[j][right] = num++;
            }
            right--;
            for(int j = right; j >= left; j--){
                vec_vec_int[bottom][j] = num++;
            }
            bottom--;
            for(int j = bottom; j >= top; j--){
                vec_vec_int[j][left] = num++;
            }
            left++;
        }
        return vec_vec_int;
    }
};

Accepted
20/20 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 49.61 % of cpp submissions (6.4 MB)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值