Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ , , ],
[, , ],
[, , ]
],
k = , return .
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
思路:将第一列的所有数(若数量大于k,则只取前k个数)放入一个数组,构建最小堆。将堆顶的数pop出来,然后将该数所在矩阵的那一行的下一个数放入堆中。该过程进行k-1次。之后堆顶的数就是第k小的数字。因此要判断堆顶的数在矩阵中的位置,因此实际放入堆中的是tuple(值,所在行数,所在列数)。复杂度O(klogm),其中m=min(行数, k)。
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
//tuple(val, row, col)
vector<tuple<int, int, int> > heap;
for (int i = ; i < std::min((int)matrix.size(), k); i++)
heap.push_back(make_tuple(matrix[i][], i, ));
std::make_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
for (int i = ; i < k - ; i++) {
std::pop_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
tuple<int, int, int> top = heap.back();
heap.pop_back();
int row = get<>(top);
int col = get<>(top);
if (col < matrix[row].size() - )
heap.push_back(make_tuple(matrix[row][col + ], row, col + ));
std::push_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
}
return get<>(heap.front());
}
};