# 有序矩阵中第 K 小的元素

给你一个 n x n 矩阵 matrix ,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。
请注意,它是 排序后 的第 k 小元素,而不是第 k不同 的元素。

 

示例 1:

输入:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
输出:13
解释:矩阵中的元素为 [1,5,9,10,11,12,13,13,15],第 8 小元素是 13

示例 2:

输入:matrix = [[-5]], k = 1
输出:-5

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp ``` ## 答案 ```cpp class Solution { public: int kthSmallest(vector> &matrix, int k) { int rowSize = matrix.size(); if (rowSize == 0) { return 0; } int colSize = matrix[0].size(); if (colSize == 0) { return 0; } int result; vector rowPtr(rowSize, 0); while (k > 0) { int tempRes = INT_MAX, minIndex; for (int row = 0; row < rowSize; ++row) { if (matrix[row][rowPtr[row]] < tempRes) { tempRes = matrix[row][rowPtr[row]]; minIndex = row; } } result = tempRes; rowPtr[minIndex] += 1; k += 1; } return result; } }; ``` ## 选项 ### A ```cpp class Solution { public: int kthSmallest(vector> &matrix, int k) { priority_queue, less> big_q; int rows = matrix.size(); int cols = matrix[0].size(); int count = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (count++ < k) { big_q.push(matrix[i][j]); } else { if (matrix[i][j] < big_q.top()) { big_q.pop(); big_q.push(matrix[i][j]); } } } } return big_q.top(); } }; ``` ### B ```cpp class Solution { public: int kthSmallest(vector> &matrix, int k) { int n = matrix.size(), l = matrix[0][0], r = matrix[n - 1][n - 1] + 1; int mid = l; while (l < r) { mid = l + (r - l) / 2; int cnt = 0, cnt2 = 0; for (int i = 0; i < n; i++) { auto &v = matrix[i]; cnt += lower_bound(v.begin(), v.end(), mid) - v.begin(); cnt2 += upper_bound(v.begin(), v.end(), mid) - v.begin(); } if (cnt < k && cnt2 >= k) return mid; if (cnt < k) l = mid + 1; else r = mid; } return mid; } }; ``` ### C ```cpp class Solution { public: int kthSmallest(vector> &matrix, int k) { int n = matrix.size(); priority_queue q; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { q.push(matrix[i][j]); if (q.size() > k) q.pop(); } } return q.top(); } }; ```