banner
cells

cells

为美好的世界献上 code

1329. マトリックスを対角線でソートする

1329. 将矩阵按对角线排序#

矩阵对角线は、行列の最上部の行または最左部の列から始まる対角線であり、右下方向に行き、行列の最後の要素まで続きます。例えば、行列matは 6 行 3 列であり、mat[2][0]から始まる矩阵の対角線は、mat[2][0]mat[3][1]mat[4][2]を通ります。

m * nの整数行列matが与えられるので、同じ矩阵の対角線上の要素を昇順に並べ替えて、並べ替えられた行列を返してください。

例 1:

img

入力:mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
出力:[[1,1,1,1],[1,2,2,2],[1,2,3,3]]

例 2:

入力:mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
出力:[[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]

ヒント:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • 1 <= mat[i][j] <= 100

シミュレーション#

class Solution {
public:
    vector<vector<int>> diagonalSort(vector<vector<int>> &mat) {
        /*
        00 01 02 03
        10 11 12 13
        20 21 22 23
         */
        /*
        {3,3,1,1},
        {2,2,1,2},
        {1,1,1,2}
         */
        int m = mat.size(), n = mat[0].size();
        // 横方向の走査
        for (int i = 0; i < n; ++i) {
            int x = 0, y = i;
            vector<int> line;
            while (x < m && y < n) {
                line.push_back(mat[x][y]);
                ++x;
                ++y;
            }
            sort(line.begin(), line.end());
            x = 0, y = i;
            while (x < m && y < n) {
                mat[x][y] = line[x];
                ++x;
                ++y;
            }
        }
        // 縦方向の走査
        for (int j = 1; j < m; ++j) {
            int x = j, y = 0;
            vector<int> line;
            while (x < m && y < n) {
                line.push_back(mat[x++][y++]);
            }
            sort(line.begin(), line.end());
            x = j, y = 0;
            while (x < m && y < n) {
                mat[x][y] = line[y];
                ++x;
                ++y;
            }
        }
        return mat;
    }
};
読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。