|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * 1329. Sort the Matrix Diagonally |
| 9 | + * |
| 10 | + * Given a m * n matrix mat of integers, |
| 11 | + * sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array. |
| 12 | + * |
| 13 | + * Example 1: |
| 14 | + * Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] |
| 15 | + * Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] |
| 16 | + * |
| 17 | + * Constraints: |
| 18 | + * m == mat.length |
| 19 | + * n == mat[i].length |
| 20 | + * 1 <= m, n <= 100 |
| 21 | + * 1 <= mat[i][j] <= 100 |
| 22 | + * */ |
| 23 | +public class _1329 { |
| 24 | + public static class Solution1 { |
| 25 | + public int[][] diagonalSort(int[][] mat) { |
| 26 | + int m = mat.length; |
| 27 | + int n = mat[0].length; |
| 28 | + int[][] sorted = new int[m][n]; |
| 29 | + for (int i = m - 1; i >= 0; i--) { |
| 30 | + int iCopy = i; |
| 31 | + List<Integer> list = new ArrayList<>(); |
| 32 | + for (int j = 0; j < n && iCopy < m; j++, iCopy++) { |
| 33 | + list.add(mat[iCopy][j]); |
| 34 | + } |
| 35 | + Collections.sort(list); |
| 36 | + iCopy = i; |
| 37 | + for (int j = 0; j < n && iCopy < m; j++, iCopy++) { |
| 38 | + sorted[iCopy][j] = list.get(j); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + for (int j = n - 1; j > 0; j--) { |
| 43 | + int jCopy = j; |
| 44 | + List<Integer> list = new ArrayList<>(); |
| 45 | + for (int i = 0; i < m && jCopy < n; i++, jCopy++) { |
| 46 | + list.add(mat[i][jCopy]); |
| 47 | + } |
| 48 | + Collections.sort(list); |
| 49 | + jCopy = j; |
| 50 | + for (int i = 0; i < m && jCopy < n; i++, jCopy++) { |
| 51 | + sorted[i][jCopy] = list.get(i); |
| 52 | + } |
| 53 | + } |
| 54 | + return sorted; |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments