-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain1.cc
More file actions
33 lines (27 loc) · 782 Bytes
/
main1.cc
File metadata and controls
33 lines (27 loc) · 782 Bytes
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
#include <queue>
#include <utility>
#include <vector>
using namespace std;
// 行头堆的思路
class Solution {
using P = pair<int, int>;
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int m = matrix.size();
int n = matrix[0].size();
// 小顶堆
auto cmp = [&](const P& a, const P& b) {
return matrix[a.first][a.second] > matrix[b.first][b.second];
};
priority_queue<P, vector<P>, decltype(cmp)> q(cmp);
for (int i = 0; i < m; i++) q.push({i, 0});
int ans = 0;
while (k-- && !q.empty()) {
auto [i, j] = q.top();
ans = matrix[i][j];
q.pop();
if (j + 1 < n) q.push({i, j + 1});
}
return ans;
}
};