-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthSmallestInSortedMatrix.cpp
More file actions
36 lines (32 loc) · 1 KB
/
KthSmallestInSortedMatrix.cpp
File metadata and controls
36 lines (32 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int minVal = matrix[0][0], maxVal = matrix[n-1][n-1];
while(minVal <= maxVal){
int mid = minVal + (maxVal - minVal)/2;
int x = 0;
for(int i = 0; i < n; i++){
x += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if(x < k)minVal = mid + 1;
else maxVal = mid - 1;
}
return minVal;
}
};
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.push(matrix[i][j]);
if(pq.size() > k) {
pq.pop();
}
}
}
return pq.top();
}
};