|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + //TC: O(r*c*log k) | SC: O(k) |
| 4 | + //This approach doesnt use the advantage of sorted property of rows and columns |
| 5 | +// int kthSmallest(vector<vector<int>>& matrix, int k) { |
| 6 | +// if(matrix.size() == 0 or k == 0) return -1; |
| 7 | + |
| 8 | +// priority_queue<int> maxHeap; |
| 9 | + |
| 10 | +// for(int r = 0; r < matrix.size(); r++) { |
| 11 | +// for(int c = 0; c < matrix[r].size(); c++) { |
| 12 | +// maxHeap.emplace(matrix[r][c]); |
| 13 | +// if(maxHeap.size() > k) maxHeap.pop(); |
| 14 | +// } |
| 15 | +// } |
| 16 | +// return maxHeap.top(); |
| 17 | +// } |
| 18 | + |
| 19 | + |
| 20 | + //since all the rows and cols are sorted, we can observe the problems as finding kth smallest element from sorted rows using min heap |
| 21 | + //optimization based on this post - https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/1322101/C%2B%2BJavaPython-MaxHeap-MinHeap-Binary-Search-Picture-Explain-Clean-and-Concise |
| 22 | + |
| 23 | + //TC: O(k * log k) | SC: O(k) |
| 24 | + int kthSmallest(vector<vector<int>>& matrix, int k) { |
| 25 | + if(matrix.size() == 0 or k == 0) return -1; |
| 26 | + int m = matrix.size(), n = matrix[0].size(); |
| 27 | + |
| 28 | + priority_queue<vector<int>, vector<vector<int>>, greater<> > minHeap; |
| 29 | + for(int r = 0; r < min(m, k); ++r) { //min() because we always know that the kth smallest element will lie in min(total rows, kth row) |
| 30 | + minHeap.push({matrix[r][0], r, 0}); |
| 31 | + } |
| 32 | + |
| 33 | + int kthSmallest = -1; |
| 34 | + for(int i = 1; i <= k; ++i) { |
| 35 | + auto ele = minHeap.top(); |
| 36 | + kthSmallest = ele[0]; |
| 37 | + int r = ele[1]; |
| 38 | + int c = ele[2]; |
| 39 | + |
| 40 | + minHeap.pop(); |
| 41 | + if(c + 1 < n) { |
| 42 | + minHeap.push({matrix[r][c+1], r, c+1}); |
| 43 | + } |
| 44 | + } |
| 45 | + return kthSmallest; |
| 46 | + } |
| 47 | + |
| 48 | +}; |
0 commit comments