Given a m * n matrix mat of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array.
Example 1:
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100
hint1:Use a data structure to store all values of each diagonal.
hint2:How to index the data structure with the id of the diagonal?
hint3:All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
左上到右下排序
answer one
Explanation
A[i][j] on the same diagonal have same value of i - j
For each diagonal,
put its elements together, sort, and set them back.
Complexity
Time O(MNlogD), where D is the length of diagonal with D = min(M,N).
Space O(MN)
i-j相同的属于一列
public int[][] diagonalSort(int[][] A) {
int m = A.length, n = A[0].length;
HashMap<Integer, PriorityQueue<Integer>> d = new HashMap<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
d.putIfAbsent(i - j, new PriorityQueue<>());
d.get(i - j).add(A[i][j]);
}
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
A[i][j] = d.get(i - j).poll();
return A;
}
answer two
class Solution {
public int[][] diagonalSort(int[][] mat) {
int m = mat.length, n = mat[0].length;
HashMap<Integer, PriorityQueue<Integer>> dict = new HashMap<>();
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (!dict.containsKey(r - c)) dict.put(r - c, new PriorityQueue<>());
dict.get(r - c).add(mat[r][c]);
}
}
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
mat[r][c] = dict.get(r - c).poll();
}
}
return mat;
}
}