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

原文链接: https://www.cnblogs.com/dysjtu1995/p/12665106.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    378. Kth Smallest Element in a Sorted Matrix

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/340953

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午12:51
下一篇 2023年3月2日 上午12:51

相关推荐