|
| 1 | +/** |
| 2 | + * 1329. Sort the Matrix Diagonally |
| 3 | + * https://leetcode.com/problems/sort-the-matrix-diagonally/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost |
| 7 | + * row or leftmost column and going in the bottom-right direction until reaching the matrix's |
| 8 | + * end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, |
| 9 | + * includes cells mat[2][0], mat[3][1], and mat[4][2]. |
| 10 | + * |
| 11 | + * Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return |
| 12 | + * the resulting matrix. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[][]} mat |
| 17 | + * @return {number[][]} |
| 18 | + */ |
| 19 | +var diagonalSort = function(mat) { |
| 20 | + const rows = mat.length; |
| 21 | + const cols = mat[0].length; |
| 22 | + const diagonals = new Map(); |
| 23 | + |
| 24 | + for (let i = 0; i < rows; i++) { |
| 25 | + for (let j = 0; j < cols; j++) { |
| 26 | + const diagonalKey = i - j; |
| 27 | + if (!diagonals.has(diagonalKey)) { |
| 28 | + diagonals.set(diagonalKey, []); |
| 29 | + } |
| 30 | + diagonals.get(diagonalKey).push(mat[i][j]); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + diagonals.forEach(values => values.sort((a, b) => a - b)); |
| 35 | + |
| 36 | + for (let i = 0; i < rows; i++) { |
| 37 | + for (let j = 0; j < cols; j++) { |
| 38 | + const diagonalKey = i - j; |
| 39 | + mat[i][j] = diagonals.get(diagonalKey).shift(); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return mat; |
| 44 | +}; |
0 commit comments