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.
先送你一句话:
why? 因为用堆做实在是太简单了,根本不用去考虑二维数组( matrix) 里的数字究竟是s型递增还是其他,just put them all into a max heap, and poll() untill there's only k elements in the heap. 我们要找的就是剩下的元素里最大的那个, 所以peek()一下就好了。 注意一下,默认的PriorityQueue是一个minHeap, 所以要自己改写Comparator.
顺便回忆了一下如何写PriorityQueue的Constructor以及自定义Comparator.
PriorityQueue(int initialCapacity, Comparator<? super [E]> comparator)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<Integer> pq = new PriorityQueue<>(n * n, maxHeap);
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
pq.add(matrix[i][j]);
}
}
while (pq.size() > k){
pq.poll();
}
return pq.peek();
}
private Comparator<Integer> maxHeap = new Comparator<Integer>(){
public int compare(Integer a, Integer b){
return b - a;
}
};
}
这道题是可以继续优化的,但我还暂时看不懂http://www.jiuzhang.com/solutions/kth-smallest-number-in-sorted-matrix/
的解法。