[leetcode] 378. Kth Smallest Element in a Sorted Matrix

网友投稿 644 2022-10-02

[leetcode] 378. Kth Smallest Element in a Sorted Matrix

[leetcode] 378. Kth Smallest Element in a Sorted Matrix

Description

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 ≤ n^2.

分析

题目的意思是:找出一个矩阵中第k小的值。

使用一个最大堆,然后遍历数组每一个元素,将其加入堆,根据最大堆的性质,大的元素会排到最前面,然后我们看当前堆中的元素个数是否大于k,大于的话就将首元素去掉,循环结束后我们返回堆中的首元素即为所求。

代码

class Solution {public: int kthSmallest(vector>& matrix, int k) { priority_queue q; int m=matrix.size(); int n=matrix[0].size(); for(int i=0;ik){ q.pop(); } } } return q-(); }};

参考文献

​​[LeetCode] Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序开发中var that =this的基本用法(微信小程序开发中负责页面显示样式的文件类型是?)
下一篇:什么是骨架屏(Skeleton Screen)?(骨架屏什么时候使用)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~