LeetCode刷题实战378:有序矩阵中第 K 小的元素
共 3275字,需浏览 7分钟
·
2021-09-13 16:00
Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
示例
示例 1:
输入:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
输出:13
解释:矩阵中的元素为 [1,5,9,10,11,12,13,13,15],第 8 小元素是 13
示例 2:
输入:matrix = [[-5]], k = 1
输出:-5
解题
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
priority_queue<int> pq;
for(int i=0;i<matrix.size();i++){
for(int j=0;j<matrix[0].size();j++){
pq.emplace(matrix[i][j]);
if(pq.size()>k) pq.pop();
}
}
return pq.top();
}
};
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;
}
};