描述
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]]
Note:
- m == mat.length
- n == mat[i].length
- 1 <= m, n <= 100
- 1 <= mat[i][j] <= 100
解析
根据题意,要为对角线的数字进行从小到大的排序,这里用到了一些数据结构,一个是用 defaultdict 初始化的 d 可以放 key 为数字,value 为列表的字典,存储对角线上的数字,另外就是在遍历 mat 的时候,根据每个数字自己的横纵坐标差,用 heappush 来往 d 中添加数据,这样就能将同一对角线上数字放到同样的列表中,最后再遍历 mat ,使用 heappush 来提取出每个坐标上的横纵坐标差对应列表中的最小值,对该位置上面的值重新赋值,遍历结束返回 mat 即可。
解答
class Solution(object):
def diagonalSort(self, mat):
"""
:type mat: List[List[int]]
:rtype: List[List[int]]
"""
d = defaultdict(list)
n,m = len(mat), len(mat[0])
for i in range(n):
for j in range(m):
heappush(d[i-j], mat[i][j])
for i in range(n):
for j in range(m):
mat[i][j] = heappop(d[i-j])
return mat
运行结果
Runtime: 76 ms, faster than 30.65% of Python online submissions for Sort the Matrix Diagonally.
Memory Usage: 14 MB, less than 11.61% of Python online submissions for Sort the Matrix Diagonally.
原题链接:leetcode.com/problems/so…
您的支持是我最大的动力