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.

先送你一句话:

Screen Shot 2017-09-28 at 4.29.06 PM.png

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/
的解法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容