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)

分析:

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

总结:

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

相关推荐
jllllyuz1 分钟前
MATLAB实现蜻蜓优化算法
开发语言·算法·matlab
AlenTech2 分钟前
208. 实现 Trie (前缀树) - 力扣(LeetCode)
leetcode
iAkuya3 分钟前
(leetcode)力扣100 36二叉树的中序遍历(迭代递归)
算法·leetcode·职场和发展
wangwangmoon_light11 分钟前
1.1 LeetCode总结(线性表)_枚举技巧
算法·leetcode·哈希算法
崎岖Qiu16 分钟前
【OS笔记36】:文件存储空间管理(一)- 空闲区表法
笔记·操作系统·存储管理·文件系统·os
菩提小狗37 分钟前
Sqlmap双击运行脚本,双击直接打开。
前端·笔记·安全·web安全
mit6.8241 小时前
几何|阻碍链
算法
有一个好名字1 小时前
力扣-小行星碰撞
算法·leetcode·职场和发展
MM_MS1 小时前
Halcon图像锐化和图像增强、窗口的相关算子
大数据·图像处理·人工智能·opencv·算法·计算机视觉·视觉检测
lamentropetion1 小时前
E - Equal Tree Sums CF1656E
算法