leetcode1329. Sort the Matrix Diagonally

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1329. 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

 

以上是关于leetcode1329. Sort the Matrix Diagonally的主要内容,如果未能解决你的问题,请参考以下文章

leetcode1329

[LeetCode] 2418. Sort the People

LeetCode | 1387. Sort Integers by The Power Value将整数按权重排序Python

LeetCode --- 1356. Sort Integers by The Number of 1 Bits 解题报告

●POJ 1329 Circle Through Three Points

Leetcode 1356. Sort Integers by The Number of 1 Bits