版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/IOT_victor/article/details/88764048
1、题目描述
数组和矩阵(378):https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。
请注意,它是排序后的第k小元素,而不是第k个元素。
示例:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, 返回 13。
说明:
你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n^2 。
2、代码详解
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
l = []
for row in matrix:
l += row
return sorted(l)[k-1]
3、其他解法
Binary Search, Heap