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();
    }
};

猜你喜欢

转载自blog.csdn.net/rockywallet/article/details/79975286
今日推荐