378. Kth Smallest Element in a Sorted Matrix

https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/

solution

  • 第k小的值,转化为其负数列表中第k大的值。在python最小堆中,最小的数

import heapq

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        if not matrix or not matrix[0]:
            return -1

        heap = []
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                heapq.heappush(heap, matrix[i][j])

        for _ in range(k):
            res = heapq.heappop(heap)
        return res

时间复杂度:O() 空间复杂度:O()

  • 二分查找

Last updated