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
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; } };
相关文章推荐
- 378.leetcode Kth Smallest Element in a Sorted Matrix(medium)[堆求第K小的 ]
- LeetCode 378. Kth Smallest Element in a Sorted Matrix (Medium)
- leetcode378:Kth Smallest Element in a Sorted Matrix(medium)
- 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】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【M】【88ms】
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- leetcode :Binary Search:Kth Smallest Element in a Sorted Matrix(378)
- 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 解题报告