-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth_smallest_number_in_sorted_matrix.cpp
More file actions
53 lines (44 loc) · 1.31 KB
/
kth_smallest_number_in_sorted_matrix.cpp
File metadata and controls
53 lines (44 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
/**
* @param matrix: a matrix of integers
* @param k: an integer
* @return: the kth smallest number in the matrix
*/
class Element {
public:
int val, row, col;
Element(int a, int b, int c) {
this->val = a;
this->row = b;
this->col = c;
}
};
struct Comparator {
bool operator() (const Element& a, const Element& b) {
return a.val > b.val;
}
};
int kthSmallest(vector<vector<int> > &matrix, int k) {
// write your code here
int row = matrix.size();
if (row == 0) return -1;
int col = matrix[0].size();
if (col == 0) return -1;
priority_queue<Element, vector<Element>, Comparator> min_heap;
for (int i = 0; i < row; i++) {
min_heap.push(Element(matrix[i][0], i, 0));
}
while (k > 1) {
const Element& it = min_heap.top();
int r = it.row;
int c = it.col;
min_heap.pop();
if (c + 1 < col) {
min_heap.push(Element(matrix[r][c + 1], r, c + 1));
}
k--;
}
return min_heap.top().val;
}
};