搜索
您的当前位置:首页正文

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

来源:步旅网

一、题目

1、题目描述

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、原题链接


二、解题报告

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;
    }
};

因篇幅问题不能全部显示,请点此查看更多更全内容

Top