Leetcode 378. Kth smallest element in ordered matrix

topic

Insert image description here
Leetcode 378. Kth smallest element in ordered matrix

Code (9.12 first brush to see the analysis)

priority queue

class Solution {
    
    
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
    
    
        int m = matrix.size(), n = matrix[0].size();
        priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> q;
        for(int i = 0; i < m; i++)
            q.push({
    
    matrix[i][0], i, 0});
        while(!q.empty() && k) {
    
    
            k--;
            auto cur = q.top();
            q.pop();
            if(k == 0) {
    
    
                return cur[0];
            }
            int i = cur[1], j = cur[2];
            if(j+1 < n) {
    
    
                q.push({
    
    matrix[i][j+1], i, j+1});
            }
        }
        return -1;
    }
};

Guess you like

Origin blog.csdn.net/weixin_51322383/article/details/132824045