【java】1329. Sort the Matrix Diagonally

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;
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值