Leetcode 1329.将矩阵按对角线排序(Sort the Matrix Diagonally)

Leetcode 1329.将矩阵按对角线排序

1 题目描述(Leetcode题目链接)

  给你一个 m * n 的整数矩阵 mat ,请你将同一条对角线上的元素(从左上到右下)按升序排序后,返回排好序的矩阵。

Leetcode 1329.将矩阵按对角线排序(Sort the Matrix Diagonally)_第1张图片

输入:mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
输出:[[1,1,1,1],[1,2,2,2],[1,2,3,3]]

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • 1 <= mat[i][j] <= 100

2 题解

  把每条对角线记下来再排序赋值。

class Solution:
    def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        x, y = m - 1, 0
        while y < n:
            cur = []
            j, k = x, y
            while j < m and k < n:
                cur.append(mat[j][k])
                j, k = j+1, k+1
            cur.sort(reverse = True)
            j, k = x, y
            while j < m and k < n:
                mat[j][k] = cur.pop()
                j, k = j+1, k+1
            if not x: 
                y += 1 
            else: 
                x -= 1
        return mat

你可能感兴趣的:(Leetcode,leetcode,算法)