|
1 | 1 | // Time: O(klog(min(m, n, k)) |
2 | 2 | // Space: O(min(m, n, k)) |
3 | 3 |
|
4 | | -// BST solution. |
5 | 4 | 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 { |
6 | 45 | public: |
7 | 46 | /** |
8 | 47 | * @param matrix: a matrix of integers |
@@ -77,7 +116,7 @@ class Solution { |
77 | 116 | // Time: O(klog(min(m, n, k)) |
78 | 117 | // Space: O(min(m, n, k)) |
79 | 118 | // Heap solution. |
80 | | -class Solution2 { |
| 119 | +class Solution3 { |
81 | 120 | public: |
82 | 121 | struct Compare { |
83 | 122 | bool operator()(const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b) { |
|
0 commit comments