LeetCode Solutions
378. Kth Smallest Element in a Sorted Matrix
Time: $O(x + k\log x)$, where $x = \min(n, k)$ Space: $O(x)$, where $x = \min(n, k)$
struct T {
int i;
int j;
int num; // matrix[i][j]
T(int i, int j, int num) : i(i), j(j), num(num) {}
};
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
auto compare = [&](const T& a, const T& b) { return a.num > b.num; };
priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);
for (int i = 0; i < k && i < matrix.size(); ++i)
minHeap.emplace(i, 0, matrix[i][0]);
while (k-- > 1) {
const auto [i, j, _] = minHeap.top();
minHeap.pop();
if (j + 1 < matrix[0].size())
minHeap.emplace(i, j + 1, matrix[i][j + 1]);
}
return minHeap.top().num;
}
};
class T {
public int i;
public int j;
public int num; // matrix[i][j]
public T(int i, int j, int num) {
this.i = i;
this.j = j;
this.num = num;
}
}
class Solution {
public int kthSmallest(int[][] matrix, int k) {
Queue<T> minHeap = new PriorityQueue<>((a, b) -> a.num - b.num);
for (int i = 0; i < k && i < matrix.length; ++i)
minHeap.offer(new T(i, 0, matrix[i][0]));
while (k-- > 1) {
final int i = minHeap.peek().i;
final int j = minHeap.poll().j;
if (j + 1 < matrix[0].length)
minHeap.offer(new T(i, j + 1, matrix[i][j + 1]));
}
return minHeap.peek().num;
}
}
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
minHeap = [] # (matrix[i][j], i, j)
i = 0
while i < k and i < len(matrix):
heapq.heappush(minHeap, (matrix[i][0], i, 0))
i += 1
while k > 1:
k -= 1
_, i, j = heapq.heappop(minHeap)
if j + 1 < len(matrix[0]):
heapq.heappush(minHeap, (matrix[i][j + 1], i, j + 1))
return minHeap[0][0]