leetcode_378 Kth Smallest Element in a Sorted Matrix
来源:互联网 发布:mysql获取前十条记录 编辑:程序博客网 时间:2024/06/14 02:37
题目分析
给定一个n*n的矩阵,其中每一行每一列都按照递增排序,寻找矩阵中的第k小元素。注意,是要寻找排好序的第k小元素,而不是第k个不重复元素。
解题思路
1)利用堆来实现。直接维护一个大小为k的堆,全部读入一边,这样平均和最好时间情况都为O(n*logk)。
2)利用二分查找实现。C++实现
struct Node{ int val; int i; int j; Node(int i, int j, int val) : i(i), j(j), val(val) { } bool operator < (const Node& x) const { return val > x.val; }};// 利用堆实现int kthSmallest1(vector< vector<int> >& matrix, int k){ priority_queue<Node> que; int n = matrix.size(); que.push(Node(0, 0, matrix[0][0])); while (--k) { Node x = que.top(); que.pop(); if (x.i == 0 && x.j + 1 < n) que.push(Node(x.i, x.j + 1, matrix[x.i][x.j + 1])); if (x.i + 1 < n) que.push(Node(x.i + 1, x.j, matrix[x.i + 1][x.j])); } return que.top().val;}// 利用二分查找实现int kthSmallest(vector< vector<int> >& matrix, int k){ int n = matrix.size(); int L = matrix[0][0]; int R = matrix[n - 1][n - 2]; while (L < R) { int mid = L + ((R - L) >> 1); int temp = 0; for (int i = 0; i < n; i++) temp += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin(); if (temp < k) L = mid + 1; else R = mid + 1; } return L;}
- 参考文献
https://www.hrwhisper.me/leetcode-kth-smallest-element-sorted-matrix/
0 0
- leetcode_378 Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix
- 【Leetcode】Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix 解题报告
- LeetCode—378. Kth Smallest Element in a Sorted Matrix
- Leetcode 378. Kth Smallest Element in a Sorted Matrix
- [leetcode] 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- 【leetcode】378. Kth Smallest Element in a Sorted Matrix
- LeetCode[378] Kth Smallest Element in a Sorted Matrix
- LeetCode:378 Kth Smallest Element in a Sorted Matrix
- leetcode之 Kth Smallest Element in a Sorted Matrix
- list
- Android 热补丁技术——资源的热修复
- 51nod oj 1100 斜率最大
- 100个弹框设计小结
- 排序数组合并
- leetcode_378 Kth Smallest Element in a Sorted Matrix
- php服务器需要定时刷新数据库问题
- CUDA入门(六) 异步并行执行解析
- 动态分配
- 直接插入排序
- struts2中s:select标签的使用
- HDU 1159 Common Subsequence(LCS)
- Java设计模式—观察者(Observer)
- 行政区域划分