|
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)) |
3 | 3 |
|
4 | 4 | class Solution {
|
5 | 5 | public:
|
6 | 6 | int kthSmallest(vector<vector<int>>& matrix, int k) {
|
7 | 7 | int kth_smallest = 0;
|
8 | 8 |
|
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 | + } |
23 | 20 | }
|
| 21 | + }; |
24 | 22 |
|
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); |
27 | 32 | }
|
28 |
| - |
29 |
| - kth_smallest = matrix[idx.first][idx.second]; |
30 | 33 | }
|
31 |
| - |
32 |
| - return kth_smallest; |
| 34 | + return kth_smallest; |
33 | 35 | }
|
34 | 36 | };
|
0 commit comments