1 题目
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
2 标准解
2.1 分析
可以遍历矩阵后,建立起堆,将前k-1个元素删掉后,堆顶即是。
也可以使用二分查找,最小值是矩阵左上角,最大值是矩阵右上角,判断中值在矩阵中的次序,如果次序比k小,说明第k个元素还要大一些,如果次序比k大说明,第k个元素还要小一些。
2.2 代码
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int left = matrix[0][0], right = matrix.back().back();
while (left < right) {
int mid = left + (right - left) / 2, cnt = 0;
for (int i = 0; i < matrix.size(); ++i) {
cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if (cnt < k) left = mid + 1;
else right = mid;
}
return left;
}
};
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
priority_queue<int> saver;
for(int i = 0; i < matrix[0].size();i++){
for(int j = 0; j < matrix[0].size();j++){
saver.emplace(matrix[i][j]);
if(saver.size() >k)
saver.pop();
}
}
return saver.top();
}
};