Kth Smallest Element in a Sorted Matrix - Medium - L

less than 1 minute read

Published:

Question

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

Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix.

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

Approach

  • Heaps

Solution

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int n = matrix.size();
        if(n==0){
            return 0;
        }
        priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq;
        for(int i=0;i<n;i++){
            pq.push(make_pair(matrix[0][i], make_pair(0, i)));
        }
        int ans;
        for(int i=0;i<k;i++){
            int c,r;
            ans = pq.top().first;
            r = pq.top().second.first;
            c = pq.top().second.second;
            pq.pop();
            if(r<n-1){
                pq.push(make_pair(matrix[r+1][c], make_pair(r+1, c)));
            }
        }
        return ans;
    }
};