# LeetCode Kth Smallest Element in a Sorted Matrix

LeetCode 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 ≤ k ≤ n2.

```class Solution {
private:
struct Node {
int val, row, col;
Node(int v = 0, int r = 0, int c = 0) :val(v), row(r), col(c) {};
friend bool operator<(const Node& n1, const Node& n2) {
return n1.val > n2.val;
}
};
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
priority_queue<Node> pn;
for (int i = 0; i < n; ++i)pn.push(Node(matrix[i][0], i, 0));
Node t;
while (k--) {
t = pn.top();
pn.pop();
if (t.col < n - 1)pn.push(Node(matrix[t.row][t.col + 1], t.row, t.col + 1));
}
return t.val;
}
};
```

```class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size(), left = matrix[0][0], right = matrix[n - 1][n - 1];
while (left <= right) {
int mid = left + (right - left) / 2;
int cnt = 0;
for (int i = 0; i < n; ++i) {
cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if (cnt < k)left = mid + 1;
else right = mid - 1;
}
return left;
}
};
```

```class Solution {
private:
int count_less_equal(vector<vector<int>>& matrix, int num) {
int n = matrix.size(), i = n - 1, j = 0, cnt = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] <= num) {
cnt += i + 1;
++j;
}
else --i;
}
return cnt;
}
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size(), left = matrix[0][0], right = matrix[n - 1][n - 1];
while (left <= right) {
int mid = left + (right - left) / 2;
int cnt = count_less_equal(matrix, mid);
if (cnt < k)left = mid + 1;
else right = mid - 1;
}
return left;
}
};
```