188 - 378 有序矩阵中第k小的元素
题目
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 请注意,它是排序后的第k小元素,而不是第k个元素。
示例:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8,
返回 13。
说明: 你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n2 。
解答
最方便方法,是拍扁成一维再排序
在这基础上优化,是小顶堆
双指针
双指针关键是搜索空间。
如果是有序数组,可以将索引作为索引;
如果是无序数组,可以将值作为索引。
这题中,找到最小数和最大数的中间值,然后计算数组中小于等于mid的元素个数,拿这个和k比较。
Runtime: 172 ms, faster than 96.86% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix.
Memory Usage: 18.6 MB, less than 9.09% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix.
这个用来统计count的方法非常巧妙啊,利用了数组都是升序的特点。
先用一行最大的数字比较,选择行;
然后在该行向前走,找到mid;
count的值就直接通过mid的索引来求
stefanPochmann的代码优化版:
Runtime: 180 ms, faster than 90.76% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix.
Memory Usage: 18.6 MB, less than 9.09% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix.
看起来更简洁了,但是更花时间😂
数学题
完全看不懂的数学题版本,评论区也是一片哀嚎,哭着点赞
感觉这应该是全leet最难的数学题了吧。。😂
虽然是一个很酷的算法,但好像超过递归栈的极限了
Last updated
Was this helpful?