【leetcode】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

解题思路:分别对每个对角线单独排序吧,简单直接。

代码如下:

class Solution(object):
    def diagonalSort(self, mat):
        """
        :type mat: List[List[int]]
        :rtype: List[List[int]]
        """
        for i in range(len(mat[0])):
            arr = []
            x,y = 0,i
            while x < len(mat) and y < len(mat[0]):
                arr.append(mat[x][y])
                x += 1
                y += 1
            arr.sort()
            
            x,y = 0,i
            while x < len(mat) and y < len(mat[0]):
                mat[x][y] = arr.pop(0)
                x += 1
                y += 1
            
        
        for i in range(1,len(mat)):
            arr = []
            x,y = i,0
            while x < len(mat) and y < len(mat[0]):
                arr.append(mat[x][y])
                x += 1
                y += 1
            arr.sort()
            
            x,y = i,0
            while x < len(mat) and y < len(mat[0]):
                mat[x][y] = arr.pop(0)
                x += 1
                y += 1
        return mat

猜你喜欢

转载自www.cnblogs.com/seyjs/p/12236377.html
今日推荐