题目:有序矩阵中第K小的元素
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。
请注意,它是排序后的第k小元素,而不是第k个元素。
示例:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]],
k = 8, 返回 13。
说明:
你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n2 。
-----------------------------------------------------------------------------------------
解法1:将二维数组中所有元素取出排序
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
li = []
for ma in matrix:
li.extend(ma)
li.sort()
return li[k-1]
解法2:类似“二分法”查找的方法
bisect.bisect_right(row, m)在row中查找m,m存在时返回m右侧的位置,m不存在返回应该插入的位置,这整行代码的意思就是数每一行row中在m值左边的个数并累加。
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
l = matrix[0][0]
r = matrix[-1][-1]
while (l < r):
m = l + (r - l) // 2
total = sum(bisect.bisect_right(row, m) for row in matrix)
if total >= k:
r = m
else:
l = m + 1
return l
参考:
https://blog.csdn.net/weixin_41303016/article/details/88571208