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.
思路:用大根堆来存储当前最小的k个数字,然后遍历矩阵,如果遍历位置数字大于等于堆顶元素,跳过该行继续遍历,否则将数字存入堆中并删除堆顶数字(保证堆中有k个数字)。最终堆顶数字即是第k小的数字。
知识点:
1.priority_queue<Type, Container, Functional>
Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。
如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。
2.nth_element算法实现
代码1:
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
vector<int> temp=matrix[0];
for(int i=1;i<matrix.size();i++){
temp.insert(temp.end(),matrix[i].begin(),matrix[i].end());
}
nth_element(temp.begin(), temp.begin()+k-1, temp.end());
return temp[k-1];
}
};
代码2/3:
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
priority_queue<int> heap;
for(int i=0; i<matrix.size(); ++i) {
for(int j=0; j<matrix[0].size(); ++j) {
if(heap.size() < k) heap.push(matrix[i][j]);
else {
if(heap.top() <= matrix[i][j]) break;
else {
heap.push(matrix[i][j]);
heap.pop();
}
}
}
}
return heap.top();
}
};