problem
LeetCode 378. Kth Smallest Element in a Sorted Matrix
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.
solution
思路过程
- 这里的问题是这个n*n矩阵即便是排好序的,但是row 和column 是单方向的排好序
- 那么,要求得低K个小的数值,
- 首先,把前每一层的数字取出来,重新排序,得到第k个小的数,这样并没有利用矩阵原有排好序的性质
- 其次,还可以怎么做呢?
- 没想出来,看别人的解答把
- 使用堆(heap)(官解中的"归并排序")思路详解;另附Python heapq模块用法解释这篇文章写得真的是好,思路很清晰,解题方法可以再次用LeetCode 23. Merge k Sorted Lists再巩固一次
代码
python
import heapq
class Solution:
def kthSmallest(self, matrix, k: int) -> int:
if matrix:
n = len(matrix)
# 将第一列的放进列表里面
heap = [(matrix[i][0], i, 0) for i in range(n)]
heapq.heapify(heap)
for i in range(k - 1):
value, row, column = heapq.heappop(heap)
# 这里row进入堆完毕的时候
if column < n-1:
heapq.heappush(heap,(matrix[row][column + 1], row, column+1))
return heapq.heappop(heap)[0]