378. Kth Smallest Element in a Sorted Matrix

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 ? n^2.

一刷
題解:
方法1: 用一個heap, 然后裝入第一行所有元素。
每次poll()一個出來,共poll() k次,得到的元素為(x, y, val), 然后在add進(x+1, y, val)

原理是:移除掉matrix中k-1個元素,在heap root的即為kth

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int m = matrix.length, n = matrix[0].length;
        PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
        for(int i=0; i<n; i++) pq.offer(new Tuple(0, i, matrix[0][i]));
        while(k>1){
            Tuple cur = pq.poll();
            if(cur.x != m-1){
               pq.offer(new Tuple(cur.x+1, cur.y, matrix[cur.x+1][cur.y])); 
            }
            k--;
        }
        return pq.poll().val;
    }
    
    class Tuple implements Comparable<Tuple>{
        int x, y, val;
        public Tuple(int x, int y, int val){
            this.x = x;
            this.y = y;
            this.val = val;
        }
        
        @Override
        public int compareTo(Tuple a){
            return this.val - a.val;
        }
    }
}

方法2: 無法理解

public int kthSmallest(int[][] matrix, int k) {
        int lo = matrix[0][0];
        int hi = matrix[matrix.length - 1][matrix[0].length - 1];
        while(lo < hi){
            int mid = lo + (hi - lo) / 2;
            int count = 0;
            int j = matrix[0].length - 1;
            for(int i = 0; i < matrix.length; i++){
                while(j >= 0 && matrix[i][j] > mid){
                    j--;
                }
                count += j + 1;
            }
            if(count < k){
                lo = mid + 1;
            }else{
                hi = mid;
            }
        }
        return lo;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容