zoukankan      html  css  js  c++  java
  • 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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    c++笔记--数组对象、vector对象和构造函数
    马加爵之歌
    周末有同学要来
    IQ
    [转]JavaScript中typeof 讲解
    【转】JS兼容Firefox
    firefox与ie 的javascript区别
    关于委托(转)
    经典常用的javascript代码收藏
    关于DataList使用DropDownList的分页实现 技巧实例源码
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12665106.html
Copyright © 2011-2022 走看看