# # 【LeetCode】378. Kth Smallest Element in a Sorted Matrix 解题报告（Python）

## # 题目描述：

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

``````Example:

matrix = [
[ 1,  5,  9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,

return 13.
``````

Note:

1. You may assume k is always valid, 1 ≤ k ≤ n2.

## # 解题方法

``````class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
nums = []
for line in matrix:
nums.extend(line)
heapq.heapify(nums)
res = 0
for i in range(k):
res = heapq.heappop(nums)
return res
``````

``````class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m, n = len(matrix), len(matrix[0])
q = [(matrix[0][0], 0, 0)]
ans = 0
for _ in range(k):
ans, i, j = heapq.heappop(q)
if j == 0 and i + 1 < m:
heapq.heappush(q, (matrix[i + 1][j], i + 1, j))
if j + 1 < n:
heapq.heappush(q, (matrix[i][j + 1], i, j + 1))
return ans
``````