leetcode :Binary Search:Kth Smallest Element in a Sorted Matrix(378)

来源:互联网 发布:淘宝宝贝详情编辑器 编辑:程序博客网 时间:2024/06/15 22:24

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.

matrix = [   [ 1,  5,  9],   [10, 11, 13],   [12, 13, 15]],k = 8,return 13.

class Solution {public:    int kthSmallest(vector<vector<int>>& matrix, int k) {        priority_queue<int, vector<int>> q;        for (int i = 0; i < matrix.size(); ++i) {            for (int j = 0; j < matrix[i].size(); ++j) {                q.emplace(matrix[i][j]);                if (q.size() > k) q.pop();            }        }        return q.top();    }};
0 0