Skip to content

Commit 2a646ad

Browse files
authored
Update kth-smallest-number-in-sorted-matrix.cpp
1 parent e32daab commit 2a646ad

1 file changed

Lines changed: 41 additions & 2 deletions

File tree

C++/kth-smallest-number-in-sorted-matrix.cpp

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,47 @@
11
// Time: O(klog(min(m, n, k))
22
// Space: O(min(m, n, k))
33

4-
// BST solution.
54
class Solution {
5+
public:
6+
/**
7+
* @param matrix: a matrix of integers
8+
* @param k: an integer
9+
* @return: the kth smallest number in the matrix
10+
*/
11+
int kthSmallest(vector<vector<int>> &matrix, int k) {
12+
int kth_smallest = 0;
13+
14+
using P = pair<int, pair<int, int>>;
15+
priority_queue<P, vector<P>, greater<P>> q;
16+
auto push = [&matrix, &q](int i, int j) {
17+
if (matrix.size() > matrix[0].size()) {
18+
if (i < matrix[0].size() && j < matrix.size()) {
19+
q.emplace(matrix[j][i], make_pair(i, j));
20+
}
21+
} else {
22+
if (i < matrix.size() && j < matrix[0].size()) {
23+
q.emplace(matrix[i][j], make_pair(i, j));
24+
}
25+
}
26+
};
27+
28+
push(0, 0);
29+
while (!q.empty() && k--) {
30+
auto tmp = q.top(); q.pop();
31+
kth_smallest = tmp.first;
32+
int i, j;
33+
tie(i, j) = tmp.second;
34+
push(i, j + 1);
35+
if (j == 0) {
36+
push(i + 1, 0);
37+
}
38+
}
39+
return kth_smallest;
40+
}
41+
};
42+
43+
// BST solution.
44+
class Solution2 {
645
public:
746
/**
847
* @param matrix: a matrix of integers
@@ -77,7 +116,7 @@ class Solution {
77116
// Time: O(klog(min(m, n, k))
78117
// Space: O(min(m, n, k))
79118
// Heap solution.
80-
class Solution2 {
119+
class Solution3 {
81120
public:
82121
struct Compare {
83122
bool operator()(const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b) {

0 commit comments

Comments
 (0)