2022-08-02 22:46:54 +02:00
|
|
|
#include <algorithm>
|
|
|
|
#include <cassert>
|
|
|
|
#include <iostream>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
class Solution {
|
2024-01-03 12:06:42 +01:00
|
|
|
public:
|
|
|
|
int kthSmallest(vector<vector<int>> &matrix, int k) {
|
2022-08-02 22:46:54 +02:00
|
|
|
int low = matrix.front().front();
|
|
|
|
int high = matrix.back().back();
|
|
|
|
|
|
|
|
while (low < high) {
|
|
|
|
int mid = low + (high - low) / 2;
|
|
|
|
|
|
|
|
int rank = 0;
|
2024-01-03 12:06:42 +01:00
|
|
|
for (const auto &row : matrix) {
|
2022-08-02 22:46:54 +02:00
|
|
|
rank += upper_bound(row.begin(), row.end(), mid) - row.begin();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (rank < k) {
|
|
|
|
low = mid + 1;
|
|
|
|
} else {
|
|
|
|
high = mid;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return low;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-01-03 12:06:42 +01:00
|
|
|
int main() {
|
2022-08-02 22:46:54 +02:00
|
|
|
Solution s;
|
|
|
|
|
|
|
|
vector<vector<int>> m;
|
|
|
|
int k;
|
|
|
|
|
2024-01-03 12:06:42 +01:00
|
|
|
m = {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}};
|
2022-08-02 22:46:54 +02:00
|
|
|
k = 8;
|
|
|
|
assert(s.kthSmallest(m, k) == 13);
|
|
|
|
|
2024-01-03 12:06:42 +01:00
|
|
|
m = {{-5}};
|
2022-08-02 22:46:54 +02:00
|
|
|
k = 1;
|
|
|
|
assert(s.kthSmallest(m, k) == -5);
|
|
|
|
}
|