-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path378.cpp
More file actions
43 lines (39 loc) · 1.25 KB
/
378.cpp
File metadata and controls
43 lines (39 loc) · 1.25 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
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int left = matrix[0][0];
int right = matrix[n - 1][n - 1];
while (left < right) {
int mid = left + (right - left) / 2;
int position = 0;
for (int i = 0; i < n; i++) {
position += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if (position >= k) right = mid;
else left = mid + 1;
}
return left;
}
};
// v2
// typedef pair<int, pair<int, int>> P; // num {x, y}
// class Solution {
// public:
// int kthSmallest(vector<vector<int>>& matrix, int k) {
// int n = matrix.size();
// priority_queue<P, vector<P>, greater<P>> pq;
// for (int i = 0; i < n; ++i) {
// pq.push(make_pair(matrix[i][0], make_pair(i, 0)));
// }
// int ans = -1;
// while (k--) {
// auto [num, idx] = pq.top();
// auto [x, y] = idx;
// ans = num;
// pq.pop();
// if (y + 1 != n) pq.push(make_pair(matrix[x][y + 1], make_pair(x, y + 1)));
// }
// return ans;
// }
// };