-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path378.cpp
55 lines (54 loc) · 1.42 KB
/
378.cpp
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
54
55
// priority_queue.cpp
class Solution {
struct Node {
int x, y;
int val;
};
struct compare {
bool operator()(Node &a, Node &b) { return a.val > b.val; }
};
public:
int kthSmallest(vector<vector<int>> &matrix, int k) {
int row = matrix.size(), col = matrix[0].size();
vector<vector<int>> visited(row, vector<int>(col, 0));
priority_queue<Node, vector<Node>, compare> qe;
qe.push(Node{0, 0, matrix[0][0]});
visited[0][0] = 1;
while (--k) {
Node cur = qe.top();
if (cur.x + 1 < row && visited[cur.x + 1][cur.y] == 0) {
qe.push(Node{cur.x + 1, cur.y, matrix[cur.x + 1][cur.y]});
visited[cur.x + 1][cur.y] = 1;
}
if (cur.y + 1 < col && visited[cur.x][cur.y + 1] == 0) {
qe.push(Node{cur.x, cur.y + 1, matrix[cur.x][cur.y + 1]});
visited[cur.x][cur.y + 1] = 1;
}
qe.pop();
}
return qe.top().val;
}
};
// sort.cpp
class Solution2 {
public:
int kthSmallest(vector<vector<int>> &matrix, int k) {
multiset<int> res;
for (auto &arr : matrix)
res.insert(arr.begin(), arr.end());
auto it = res.begin();
for (int i = 1; i < k; ++i)
++it;
return *it;
}
};
class Solution3 {
public:
int kthSmallest(vector<vector<int>> &matrix, int k) {
vector<int> res;
for (auto &arr : matrix)
res.insert(res.end(), arr.begin(), arr.end());
sort(res.begin(), res.end());
return res[k - 1];
}
};