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 分钟前
AI抢人大战:谁在收割你的红包
大数据·人工智能·算法
TracyCoder12320 分钟前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
A尘埃20 分钟前
电信运营商用户分群与精准运营(K-Means聚类)
算法·kmeans·聚类
半壶清水1 小时前
[软考网规考点笔记]-软件开发、项目管理与知识产权核心知识与真题解析
网络·笔记·压力测试
power 雀儿1 小时前
掩码(Mask)机制 结合 多头自注意力函数
算法
会叫的恐龙1 小时前
C++ 核心知识点汇总(第六日)(字符串)
c++·算法·字符串
tq10862 小时前
先探索,后设计
笔记
小糯米6012 小时前
C++顺序表和vector
开发语言·c++·算法
hnult2 小时前
2026 在线培训考试系统选型指南:核心功能拆解与选型逻辑
人工智能·笔记·课程设计
AI视觉网奇2 小时前
ue 角色驱动衣服 绑定衣服
笔记·学习·ue5