378 Kth Smallest Element in a Sorted Matrix

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 \leqslant k \leqslant n^2$$.

Solution

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int m = matrix.size();
        int n = matrix[0].size();
        priority_queue<int> maxHeap;
        for ( int i = 0; i <= m-1; i++) {
            for ( int j = 0; j <= n-1; j++ ) {
                if ( maxHeap.size() <= k-1 ) { maxHeap.push(matrix[i][j]); continue; }
                if ( matrix[i][j] > maxHeap.top() ) continue;
                maxHeap.pop();
                maxHeap.push(matrix[i][j]);
            }
        }
        return maxHeap.top();
    }
};

Notes

  1. Use a maximum heap with a size of K to find topK smallest number.
  2. How to utilize the property of "sorted matrix" to reduce time complexity?

Another solution, using the function: upper_bound(vector.begin(), vector.end(), target)

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int n = matrix.size();
        priority_queue<int> maxHeap;
        int i = 0, j = 0;
        for ( i = 0; i <= (k-1)/n; i++ ) {
            for ( int j = 0; j <= n-1; j++) {
                maxHeap.push(matrix[i][j]);
            }
        }
        while ( maxHeap.size() > k ) maxHeap.pop();
        int last_j = n-1;
        for ( i = (k-1)/n+1; i <= n-1; i++ ) {
            j = upper_bound(matrix[i].begin(), matrix[i].end(), maxHeap.top()) - matrix[i].begin() - 1;
            j = min(last_j, j);
            last_j = j;
            while ( j >= 0 ) {
                maxHeap.pop();
                maxHeap.push(matrix[i][j]);
                j -= 1;
            }
        }
        return maxHeap.top();
    }
};
  • binary search method?

results matching ""

    No results matching ""