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

一、题目

1、题目描述

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

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

2、接口描述

python3
class Solution:
    def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
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
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
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;
    }
};

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EQUINOX1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值