(Leetcode) 有序矩阵中第K小的元素 - Python实现

题目:有序矩阵中第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

https://blog.csdn.net/qq_36309480/article/details/90296367

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值