[LeetCode] Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素
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,大于的话就将首元素去掉,循环结束后我们返回堆中的首元素即为所求:
解法一:
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
priority_queue<int> q;
for (int i = ; i < matrix.size(); ++i) {
for (int j = ; j < matrix[i].size(); ++j) {
q.emplace(matrix[i][j]);
if (q.size() > k) q.pop();
}
}
return q.top();
}
};
这题我们也可以用二分查找法来做,我们由于是有序矩阵,那么左上角的数字一定是最小的,而右下角的数字一定是最大的,所以这个是我们搜索的范围,然后我们算出中间数字mid,由于矩阵中不同行之间的元素并不是严格有序的,所以我们要在每一行都查找一下 mid,我们使用 upper_bound,这个函数是查找第一个大于目标数的元素,如果目标数在比该行的尾元素大,则 upper_bound 返回该行元素的个数,如果目标数比该行首元素小,则 upper_bound 返回0, 我们遍历完所有的行可以找出中间数是第几小的数,然后k比较,进行二分查找,left 和 right 最终会相等,并且会变成数组中第k小的数字。举个例子来说吧,比如数组为:
[1 2
12 100]
k = 3
那么刚开始 left = 1, right = 100, mid = 50, 遍历完 cnt = 3,此时 right 更新为 50
此时 left = 1, right = 50, mid = 25, 遍历完之后 cnt = 3, 此时 right 更新为 25
此时 left = 1, right = 25, mid = 13, 遍历完之后 cnt = 3, 此时 right 更新为 13
此时 left = 1, right = 13, mid = 7, 遍历完之后 cnt = 2, 此时 left 更新为8
此时 left = 8, right = 13, mid = 10, 遍历完之后 cnt = 2, 此时 left 更新为 11
此时 left = 11, right = 12, mid = 11, 遍历完之后 cnt = 2, 此时 left 更新为 12
循环结束,left 和 right 均为 12,任意返回一个即可。
本解法的整体时间复杂度为 O(nlgn*lgX),其中X为最大值和最小值的差值,参见代码如下:
解法二:
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int left = matrix[][], right = matrix.back().back();
while (left < right) {
int mid = left + (right - left) / , cnt = ;
for (int i = ; i < matrix.size(); ++i) {
cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if (cnt < k) left = mid + ;
else right = mid;
}
return left;
}
};
上面的解法还可以进一步优化到 O(nlgX),其中X为最大值和最小值的差值,我们并不用对每一行都做二分搜索法,我们注意到每列也是有序的,我们可以利用这个性质,从数组的左下角开始查找,如果比目标值小,我们就向右移一位,而且我们知道当前列的当前位置的上面所有的数字都小于目标值,那么 cnt += i+1,反之则向上移一位,这样我们也能算出 cnt 的值。其余部分跟上面的方法相同,参见代码如下:
解法三:
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int left = matrix[][], right = matrix.back().back();
while (left < right) {
int mid = left + (right - left) / ;
int cnt = search_less_equal(matrix, mid);
if (cnt < k) left = mid + ;
else right = mid;
}
return left;
}
int search_less_equal(vector<vector<int>>& matrix, int target) {
int n = matrix.size(), i = n - , j = , res = ;
while (i >= && j < n) {
if (matrix[i][j] <= target) {
res += i + ;
++j;
} else {
--i;
}
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/378
类似题目:
Find K Pairs with Smallest Sums
Find K-th Smallest Pair Distance
Kth Smallest Number in Multiplication Table
参考资料:
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素的更多相关文章
- [LeetCode] 378. Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth ...
- 378 Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素.请注意,它是排序后的第k小元素,而不是第k个元素.示例:matrix = [ [ 1, 5, 9], [ ...
- [LintCode] Kth Smallest Number in Sorted Matrix 有序矩阵中第K小的数字
Find the kth smallest number in at row and column sorted matrix. Have you met this question in a rea ...
- LeetCode 378. 有序矩阵中第K小的元素(Kth Smallest Element in a Sorted Matrix) 13
378. 有序矩阵中第K小的元素 378. Kth Smallest Element in a Sorted Matrix 题目描述 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩 ...
- Leetcode 378.有序矩阵中第k小的元素
有序矩阵中第k小的元素 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素.请注意,它是排序后的第k小元素,而不是第k个元素. 示例: matrix = [ [ 1, ...
- Java实现 LeetCode 378 有序矩阵中第K小的元素
378. 有序矩阵中第K小的元素 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素. 请注意,它是排序后的第k小元素,而不是第k个元素. 示例: matrix = [ ...
- [Swift]LeetCode378. 有序矩阵中第K小的元素 | 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 ...
- 【Leetcode 堆、快速选择、Top-K问题 BFPRT】有序矩阵中第K小的元素(378)
题目 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素. 请注意,它是排序后的第k小元素,而不是第k个元素. 示例: matrix = [ [ 1, 5, 9], [ ...
- leetcode.矩阵.378有序矩阵中第K小的元素-Java
1. 具体题目 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素.请注意,它是排序后的第k小元素,而不是第k个元素. 示例: matrix = [ [ 1, 5, ...
随机推荐
- JavaScript instanceof vs typeof
Use instanceof for custom typesvar ClassFirst = function () {};var ClassSecond = function () {};var ...
- 实现跨浏览器html5表单验证
div:nth-of-type(odd){ float: left; clear: left; } .origin-effect > div:nth-of-type(even){ float: ...
- Hadoop学习之旅三:MapReduce
MapReduce编程模型 在Google的一篇重要的论文MapReduce: Simplified Data Processing on Large Clusters中提到,Google公司有大量的 ...
- C#开发微信门户及应用(19)-微信企业号的消息发送(文本、图片、文件、语音、视频、图文消息等)
我们知道,企业号主要是面向企业需求而生的,因此内部消息的交流显得非常重要,而且发送.回复消息数量应该很可观,对于大企业尤其如此,因此可以结合企业号实现内部消息的交流.企业号具有关注安全.消息无限制等特 ...
- 从ASP.NET 升级到ASP.NET5(RC1) - 翻译
前言 ASP.NET 5 是一次令人惊叹的对于ASP.NET的创新革命. 他将构建目标瞄准了 .NET Core CLR, 同时ASP.NET又是对于云服务进行优化,并且是跨平台的框架.很多文章已经称 ...
- 【Java每日一题】20161223
package Dec2016; public class Ques1223 { public static void main(String[] args){ Integer obj = Integ ...
- Linux:JDK配置
1.JDK官网下载"jdk-8u101-linux-i586.tar.gz",32位或64位. 2 命令 #创建jdk所在目录 sudo mkdir /usr/lib/jvm #找 ...
- hdu-2444-二分图判定+最大分配
The Accomodation of Students Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ( ...
- Spring的IOC和AOP之深剖
今天,既然讲到了Spring 的IOC和AOP,我们就必须要知道 Spring主要是两件事: 1.开发Bean:2.配置Bean.对于Spring框架来说,它要做的,就是根据配置文件来创建bean实例 ...
- infopath发布的提示“无法解析SOAP消息”(The SOAP message cannot be parsed)问题解决方案
最近发现一个列表数据过大,每次发布infopath表单提示如下错误: 后来发现一个infopath表单通过list.asmx and Formsservice.asmx来进行发布的. This err ...