leetcode做题笔记59

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

思路一:设置方向,每行每列按对应方向输入,最后返回

cpp 复制代码
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) {
    int maxNum = n * n;
    int curNum = 1;
    int** matrix = malloc(sizeof(int*) * n);
    *returnSize = n;
    *returnColumnSizes = malloc(sizeof(int) * n);
    for (int i = 0; i < n; i++) {
        matrix[i] = malloc(sizeof(int) * n);
        memset(matrix[i], 0, sizeof(int) * n);
        (*returnColumnSizes)[i] = n;
    }
    int row = 0, column = 0;
    int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};  
    int directionIndex = 0;
    while (curNum <= maxNum) {
        matrix[row][column] = curNum;
        curNum++;
        int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
        if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || matrix[nextRow][nextColumn] != 0) {
            directionIndex = (directionIndex + 1) % 4;  
        }
        row += directions[directionIndex][0];
        column += directions[directionIndex][1];
    }
    return matrix;
}

时间复杂度O(n),空间复杂度O(n^2)

分析:

本题要按顺时针顺序排列数组后输出,可设置对应的方向数组,将递增的数通过方向数组放置到正确的位置,最后输出数组即可

总结:

本题考察对数组的应用,想到用方向确定数位置即可解决本题

相关推荐
NAGNIP4 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队5 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja10 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下10 小时前
最终的信号类
开发语言·c++·算法
_落纸10 小时前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
茉莉玫瑰花茶10 小时前
算法 --- 字符串
算法
博笙困了10 小时前
AcWing学习——差分
c++·算法
NAGNIP10 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP10 小时前
大模型微调框架之LLaMA Factory
算法
echoarts10 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust