Description
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:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
m=len(mat)
n=len(mat[0])
for k in range(m):
i,j=k,0
diag=[]
while(i<m and j<n):
diag.append(mat[i][j])
i+=1
j+=1
diag.sort()
i-=1
j-=1
while(len(diag)>0):
mat[i][j]=diag.pop()
i-=1
j-=1
for k in range(n):
i,j=0,k
diag=[]
while(i<m and j<n):
diag.append(mat[i][j])
i+=1
j+=1
diag.sort()
i-=1
j-=1
while(len(diag)>0):
mat[i][j]=diag.pop()
i-=1
j-=1
return mat
参考文献
[LeetCode] Python program, beats 91% solutions with memory usage less than 94.99%