Skip to content

Commit 3cb7070

Browse files
authored
Update kth-smallest-element-in-a-sorted-matrix.cpp
1 parent 9ef1136 commit 3cb7070

File tree

1 file changed

+24
-22
lines changed

1 file changed

+24
-22
lines changed
Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,36 @@
1-
// Time: O(klogk)
2-
// Space: O(k)
1+
// Time: O(k * log(min(n, m, k))), with n x m matrix
2+
// Space: O(min(n, m, k))
33

44
class Solution {
55
public:
66
int kthSmallest(vector<vector<int>>& matrix, int k) {
77
int kth_smallest = 0;
88

9-
using P = pair<int, int>;
10-
const auto Compare = [&matrix](const P& a, const P& b) {
11-
return matrix[a.first][a.second] > matrix[b.first][b.second];
12-
};
13-
14-
priority_queue<P, vector<P>, decltype(Compare)> min_heap(Compare);
15-
min_heap.emplace(0, 0);
16-
17-
for (int i = 0; i < k; ++i) {
18-
const auto idx = min_heap.top();
19-
min_heap.pop();
20-
21-
if (idx.first == 0 && idx.second + 1 < matrix[0].size()) {
22-
min_heap.emplace(0, idx.second + 1);
9+
using P = pair<int, pair<int, int>>;
10+
priority_queue<P, vector<P>, greater<P>> q;
11+
auto push = [&matrix, &q](int i, int j) {
12+
if (matrix.size() > matrix[0].size()) {
13+
if (i < matrix[0].size() && j < matrix.size()) {
14+
q.emplace(matrix[j][i], make_pair(j, i));
15+
}
16+
} else {
17+
if (i < matrix.size() && j < matrix[0].size()) {
18+
q.emplace(matrix[i][j], make_pair(i, j));
19+
}
2320
}
21+
};
2422

25-
if (idx.first + 1 < matrix.size()) {
26-
min_heap.emplace(idx.first + 1, idx.second);
23+
push(0, 0);
24+
while (!q.empty() && k--) {
25+
auto tmp = q.top(); q.pop();
26+
kth_smallest = tmp.first;
27+
int i, j;
28+
tie(i, j) = tmp.second;
29+
push(i, j + 1);
30+
if (j == 0) {
31+
push(i + 1, 0);
2732
}
28-
29-
kth_smallest = matrix[idx.first][idx.second];
3033
}
31-
32-
return kth_smallest;
34+
return kth_smallest;
3335
}
3436
};

0 commit comments

Comments
 (0)