378. Kth Smallest Element in a Sorted Matrix

Given a n × n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

Note:

You may assume k is always valid, 1 ≤ k.

Solution: Heap

import heapq


class Solution(object):
    def kthSmallest(self, matrix, k):
        """
        :type matrix: List[List[int]]
        :type k: int
        :rtype: int
        """
        if not matrix:
            return -1

        q = []
        for col, num in enumerate(matrix[0][:k]):
            heapq.heappush(q, (num, 0, col))
        rows = len(matrix)
        num = None
        while k > 0 and q:
            num, row, col = heapq.heappop(q)
            if row < rows - 1:
                row += 1
                heapq.heappush(q, (matrix[row][col], row, col))
            k -= 1
        return num

Lessons:

  • For 2D problems, split 2D into 1D and 1. Push one row to heap, and after each pop, add another one to heap.

results matching ""

    No results matching ""