码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1329. Sort the Matrix Diagonally

时间:2020-01-27 19:06:23      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:class   def   解题思路   排序   技术   nal   integer   end   int   

题目如下:

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

 

【leetcode】1329. Sort the Matrix Diagonally

标签:class   def   解题思路   排序   技术   nal   integer   end   int   

原文地址:https://www.cnblogs.com/seyjs/p/12236377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!