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

152人阅读 评论(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.

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;
}
};

0
0

个人资料
• 访问：82484次
• 积分：2333
• 等级：
• 排名：第18876名
• 原创：149篇
• 转载：71篇
• 译文：0篇
• 评论：3条
阅读排行
最新评论