378. Kth Smallest Element in a Sorted Matrix

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

Problem

Given a n x 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 ≤ n2.

Solution

1. O(N2logK)O(N^2logK) using max heap

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k){
        priority_queue<int> max_heap;
        for (const auto &row: matrix) {
            for (const auto &e: row) {
                if (max_heap.size() < k) {
                    max_heap.push(e);
                    continue;
                } 
                if (e < max_heap.top()) {
                    max_heap.pop();
                    max_heap.push(e);
                }
            }
        }
        return max_heap.top();
    }
};

2. O(MlogM)O(MlogM) (M=max(K,N)(M = max(K, N) using min heap

  • #heap

  • #binarysearch

  • #important

Last updated

Was this helpful?