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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容