https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/
题目:二维数组的第k小元素。
第一种解法:直接排序。(n^2*log(n^2))
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int len=matrix[0].size(),sum=0;
int* temp=new int[len*len];
for(int x=0;x<len;x++)
for(int y=0;y<len;y++)
temp[sum]=matrix[x][y],sum++;
sort(temp,temp+(len*len));
return temp[k-1];
}
};
第二种:使用堆 (n^2*log(k))
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int len=matrix[0].size();
priority_queue<int,vector<int>,less<int>>p;
for(int x=0;x<len;x++)
for(int y=0;y<len;y++)
{
if(p.size()<k) p.push(matrix[x][y]);
else if(p.size()==k)
if(p.top()>matrix[x][y])
p.pop(),p.push(matrix[x][y]);
}
return p.top();
}
};
第三种: 二分查找
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int bgn = matrix[0][0], end = matrix[n-1][n-1];
while(bgn < end) {
int mid = (bgn + end) / 2;
int cnt = 0;
for(int i=0; i<n; ++i) {
cnt += (upper_bound(matrix[i].begin(), matrix[i].end(), mid)-matrix[i].begin());
}
if(cnt < k) bgn = mid + 1;
else end = mid;
}
return bgn;
}
};