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)

分析:

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

总结:

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

相关推荐
兴趣使然_1 小时前
【笔记】使用 html 创建网址快捷方式
笔记·html·js
卡卡卡卡罗特1 小时前
每日mysql
数据结构·算法
chao_7892 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
aramae2 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
lifallen3 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest3 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
EndingCoder3 小时前
搜索算法在前端的实践
前端·算法·性能优化·状态模式·搜索算法
丶小鱼丶3 小时前
链表算法之【合并两个有序链表】
java·算法·链表
fen_fen3 小时前
学习笔记(32):matplotlib绘制简单图表-数据分布图
笔记·学习·matplotlib
不吃洋葱.3 小时前
前缀和|差分
数据结构·算法