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.
class Solution
{
public:
int kthSmallest(vector<vector<int>> &matrix, int k)
{
int n = matrix.size();
set<pair<int, int>> s;
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> pq;
pq.push({matrix[0][0], {0, 0}});
s.insert({0, 0});
int i = 1;
while (i < k)
{
int ele = pq.top().first;
int idx1 = pq.top().second.first;
int idx2 = pq.top().second.second;
pq.pop();
if (idx1 + 1 < n)
{
if (s.find({idx1 + 1, idx2}) == s.end())
{
pq.push({matrix[idx1 + 1][idx2], {idx1 + 1, idx2}});
s.insert({idx1 + 1, idx2});
}
}
if (idx2 + 1 < n )
{
if (s.find({idx1, idx2 + 1}) == s.end())
{
pq.push({matrix[idx1][idx2 + 1], {idx1, idx2 + 1}});
s.insert({idx1, idx2 + 1});
}
}
i++;
}
return pq.top().first;
}
};