378. Kth Smallest Element in a Sorted Matrix

原题链接

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 ≤ n2.

翻译:从一个每行有序的二维数组中找到第k大的值。

思路:优先队列维护前k大。

AC代码:

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        priority_queue<int> que;
        for(int i=0;i<matrix.size();i++)
        for(int j=0;j<matrix[i].size();j++)
            que.push(matrix[i][j]);
        while(que.size()>k)
            que.pop();
        return que.top();
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rockywallet/article/details/79975286
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

378. Kth Smallest Element in a Sorted Matrix

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭