排序 + 模拟,LeetCode 1329. 将矩阵按对角线排序

一、题目

1、题目描述

矩阵对角线 是一条从矩阵最上面行或者最左侧列中的某个元素开始的对角线,沿右下方向一直到矩阵末尾的元素。例如,矩阵 mat63 列,从 mat[2][0] 开始的 矩阵对角线 将会经过 mat[2][0]mat[3][1]mat[4][2]

给你一个 m * n 的整数矩阵 mat ,请你将同一条 矩阵对角线上的元素按升序排序后,返回排好序的矩阵。

2、接口描述

python3
复制代码
python 复制代码
class Solution:
    def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
cpp
复制代码
cpp 复制代码
class Solution {
public:
    vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

    }
};

3、原题链接

1329. 将矩阵按对角线排序


二、解题报告

1、思路分析

遍历每一条对角线,放入临时数组排序完再放回去即可

2、复杂度

时间复杂度: O(mn log min(m, n)) 空间复杂度:O(min(m, n))

3、代码详解

python3
复制代码
python 复制代码
class Solution:
    def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        for i in range(m - 1, -1, -1):
            x, y = i, 0
            a = []
            while x < m and y < n:
                a.append(mat[x][y])
                x += 1
                y += 1
            x, y = i, 0
            for t in sorted(a):
                mat[x][y] = t
                x += 1
                y += 1
        for i in range(1, n):
            x, y = 0, i
            a = []
            while x < m and y < n:
                a.append(mat[x][y])
                x += 1
                y += 1
            x, y = 0, i
            for t in sorted(a):
                mat[x][y] = t
                x += 1
                y += 1

        return mat
cpp
复制代码
cpp 复制代码
class Solution {
public:
    vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
        int m = mat.size(), n = mat[0].size();
        for(int i = m - 1; ~i; i --){
            vector<int> a;
            for(int x = i, y = 0; x < m && y < n; x ++, y ++ )
                a.emplace_back(mat[x][y]);
            sort(a.begin(), a.end());
            for(int x = i, y = 0, t = 0; x < m && y < n; x ++, y ++, t ++)
                mat[x][y] = a[t];
        }
        for(int i = 1; i < n; i ++){
            vector<int> a;
            for(int x = 0, y = i; x < m && y < n; x ++, y ++ )
                a.emplace_back(mat[x][y]);
            sort(a.begin(), a.end());
            for(int x = 0, y = i, t = 0; x < m && y < n; x ++, y ++, t ++)
                mat[x][y] = a[t];
        }
        return mat;
    }
};
相关推荐
初级炼丹师(爱说实话版)3 分钟前
多进程与多线程的优缺点及适用场景总结
算法
hetao173383715 分钟前
2025-11-25~26 hetao1733837的刷题记录
c++·算法
历程里程碑32 分钟前
各种排序法大全
c语言·数据结构·笔记·算法·排序算法
少许极端42 分钟前
算法奇妙屋(十四)-简单多状态dp问题
算法·动态规划·图解算法·简单多状态dp·打家劫舍问题·买卖股票问题全解
2301_823438021 小时前
解析论文《复杂海上救援环境中无人机群的双阶段协作路径规划与任务分配》
人工智能·算法·无人机
embrace992 小时前
【C语言学习】结构体详解
android·c语言·开发语言·数据结构·学习·算法·青少年编程
Ayanami_Reii2 小时前
基础数学算法-开关问题
数学·算法·高斯消元
稚辉君.MCA_P8_Java2 小时前
通义 Go 语言实现的插入排序(Insertion Sort)
数据结构·后端·算法·架构·golang
稚辉君.MCA_P8_Java3 小时前
Gemini永久会员 Go 实现动态规划
数据结构·后端·算法·golang·动态规划
快手技术3 小时前
快手 & 南大发布代码智能“指南针”,重新定义 AI 编程能力评估体系
算法