378. Kth Smallest Element in a Sorted Matrix

29 篇文章 0 订阅
7 篇文章 0 订阅

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个数字)。最终堆顶数字即是第k小的数字。

知识点:

1.priority_queue<Type, Container, Functional>

Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。

如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。

2.nth_element算法实现

代码1:

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        vector<int> temp=matrix[0];
        for(int i=1;i<matrix.size();i++){
            temp.insert(temp.end(),matrix[i].begin(),matrix[i].end());
        }
        nth_element(temp.begin(), temp.begin()+k-1, temp.end());  
        return temp[k-1];  
    }
};

代码2/3:

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值