378. Kth Smallest Element in a Sorted Matrix

Problem:

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 = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

Note:
You may assume k is always valid, \(1 ≤ k ≤ n^2\).

思路

Solution (C++):

int kthSmallest(vector>& matrix, int k) {
    using my_pair = pair>;
    auto my_comp = [](const my_pair &x, const my_pair &y) { return x.first > y.first; };
    if (matrix.empty() || matrix[0].empty())  return -1;
    int n = matrix.size();
    priority_queue, decltype(my_comp)> minHeap(my_comp);
    
    for (int i = 0; i < n && i < k; ++i) {
        minHeap.push(make_pair(matrix[i][0], make_pair(i,0)));
    }
    
    int count = 0, res = 0;
    while (!minHeap.empty()) {
        auto heapTop = minHeap.top();
        minHeap.pop();
        res = heapTop.first;
        if (++count == k)  break;
        
        ++heapTop.second.second;
        if (n > heapTop.second.second) {
            heapTop.first = matrix[heapTop.second.first][heapTop.second.second];
            minHeap.push(heapTop);
        }
    }
    return res;
}

性能

Runtime: 104 ms  Memory Usage: 9.9 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

你可能感兴趣的:(378. Kth Smallest Element in a Sorted Matrix)