您的位置:首页 > 编程语言 > C语言/C++

Leetcode 378. Kth Smallest Element in a Sorted Matrix (Medium) (cpp)

2016-08-23 16:42 561 查看
Leetcode 378. Kth Smallest Element in a Sorted Matrix (Medium) (cpp)

Tag: Binary Search, Heap

Difficulty: Medium

/*

378. Kth Smallest Element in a Sorted Matrix (Medium)

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) {
int r = matrix.size() - 1, min = matrix[0][0], max = matrix[r][r];
while (min < max) {
int cnt = 0, mid = (min + max) / 2;
for (int i = 0; i <= r && matrix[i][0] <= mid; i++)
cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
k <= cnt ? max = mid : min = mid + 1;
}
return min;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode