classSolution { public: intkthSmallest(vector<vector<int>>& matrix, int k){ constint n = matrix.size(); priority_queue<Coord, vector<Coord>, greater<Coord>> minHeap;
// 將第一行元素加到 minHeap 中 for (int r = 0; r < n; ++r) { minHeap.emplace(r, 0, matrix[r][0]); }
for (int i = 0; i < k - 1; ++i) { constauto [r, c, val] = minHeap.top(); minHeap.pop();
// 如果 top 右邊一格還沒越界, 則將其加入到 heap 中 if (c != n - 1) { minHeap.emplace(r, c + 1, matrix[r][c + 1]); } }
return minHeap.top().val; } };
time:
:for loop, 其中 worse case 為
:insertion of heap(因為 heap 是 balanced tree, swap() 最多為樹高 次)
space: ➔ minHeap 中最多 n 個元素
Solution 3:
想法:利用 Binary Search, 其中 left = matrix[0][0], right = matrix[n - 1][n - 1] + 1, 得出 mid 後, 計算 matrix 中 ≤ mid 的個數 cnt (可參考 240. Search a 2D Matrix II 的 Z 字形搜索), 希望找到一個 mid 使得 matrix 中剛好有 k 個數 ≤ mid
cpp
classSolution { public: intkthSmallest(vector<vector<int>>& matrix, int k){ constint n = matrix.size(); int left = matrix[0][0], right = matrix[n - 1][n - 1] + 1;
while (left < right) { constint mid = left + (right - left) / 2;
if (count_less_equal(n, matrix, mid) >= k) { right = mid; } else { left = mid + 1; } }
return left; // left 為第一個有 k 個數 >= 自己 }
private: // 計算 matrix 中 ≤ mid 的元素個數, 此處也可以改成用 binary search 實作 intcount_less_equal(int& n, vector<vector<int>>& matrix, int& mid){ int cnt = 0, row = 0, col = n - 1;
while (row < n && col >= 0) { if (matrix[row][col] <= mid) { cnt += (col + 1); ++row; } else { --col; } }