-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path378.cpp
More file actions
23 lines (19 loc) · 768 Bytes
/
378.cpp
File metadata and controls
23 lines (19 loc) · 768 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Solution for https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
priority_queue<int> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix.size(); j++) {
if (maxHeap.size() <= k || matrix[i][j] <= maxHeap.top()) maxHeap.push(matrix[i][j]);
else minHeap.push(matrix[i][j]);
if (maxHeap.size() > k) {
minHeap.push(maxHeap.top());
maxHeap.pop();
}
}
}
return maxHeap.top();
}
};