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<vector<int>>& matrix, int k) {
    using my_pair = pair<int, pair<int, int>>;
    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<my_pair, vector<my_pair>, 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

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12665106.html