Leetcode 378. Kth Smallest Element in a Sorted Matrix
2017-06-22 23:28
459 查看
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:
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:
public int kthSmallest(int[][] matrix, int k) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return -1;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, (x,y) -> y - x);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
pq.offer(matrix[i][j]);
if (pq.size() > k) pq.poll();
}
}
return pq.peek();
}
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.
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.
public int kthSmallest(int[][] matrix, int k) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return -1;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, (x,y) -> y - x);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
pq.offer(matrix[i][j]);
if (pq.size() > k) pq.poll();
}
}
return pq.peek();
}
相关文章推荐
- 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 (Medium) (cpp)
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode[378] Kth Smallest Element in a Sorted Matrix
- 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 :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
- 378.leetcode Kth Smallest Element in a Sorted Matrix(medium)[堆求第K小的 ]
- LeetCode:378 Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix