1329. Sort the Matrix Diagonally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public int[][] diagonalSort(int[][] mat) {
int m = mat.length, n = mat[0].length;

List<Integer> numList = new ArrayList<>();

// right to left
for (int j = n - 1; j >= 0; j--) {
numList.clear();

for (int x = 0, y = j; x < m && y < n; x++, y++) {
numList.add(mat[x][y]);
}
Collections.sort(numList);
for (int x = 0, y = j, k = 0; x < m && y < n; x++, y++, k++) {
mat[x][y] = numList.get(k);
}
}

// top to bottom
for (int i = 1; i < m; i++) {
numList.clear();

for (int x = i, y = 0; x < m && y < n; x++, y++) {
numList.add(mat[x][y]);
}
Collections.sort(numList);
for (int x = i, y = 0, k = 0; x < m && y < n; x++, y++, k++) {
mat[x][y] = numList.get(k);
}
}

return mat;
}
}

References

1329. Sort the Matrix Diagonally