想法:利用 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
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; } }
return cnt; } };
time:$O(n \cdot log(r-l))$ ➔ r 代表 right, l 代表 left