378. Kth Smallest Element in a Sorted Matrix leetcode binary_search 378

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.

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

class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int left = matrix[0][0], right = matrix.back().back();
while (left < right) {
int mid = left + (right - left) / 2, cnt = 0;
for (int i = 0; i < matrix.size(); ++i) {
cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if (cnt < k) left = mid + 1;
else right = mid;
}
return left;
}
};

class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int left = matrix[0][0], right = matrix.back().back();
while (left < right) {
int mid = left + (right - left) / 2;
int cnt = search_less_equal(matrix, mid);
if (cnt < k) left = mid + 1;
else right = mid;
}
return left;
}
int search_less_equal(vector<vector<int>>& matrix, int target) {
int n = matrix.size(), i = n - 1, j = 0, res = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] <= target) {
res += i + 1;
++j;
} else {
--i;
}
}
return res;
}
};

Leetcode 644. Maximum Average Subarray II 最大平均区间2 解题报告

2017-07-27 22:41:33

LintCode二分查找题总结

2016-08-03 15:53:49

Leetcode题解(超赞!!!)

2018-02-23 21:31:56

【算法】LeetCode上一些经典好题（update@0617）

2016-12-06 15:26:31

LEETCODE 150题吐血大整理

2016-07-17 15:49:13

LeetCode378-有序矩阵中第k小的元素

2018-04-12 09:54:51

有序矩阵中查找第k小的元素 Kth smallest element in a row-wise and column-wise sorted 2D array

2014-11-23 04:31:01

leetcode 在有序矩阵中查找某个数，第k小数 （二分法）

2016-12-13 08:37:54

C 在行有序的矩阵中找出第k大的元素

2017-04-11 00:06:14

leetcode 378. 有序矩阵中第K小的元素

2018-05-22 21:04:19