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.

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13
public class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
            public int compare(int[] a, int[] b){
                return a[2] - b[2];
            }
        });
        
        int n = matrix.length;
        // add first row
        for(int i=0; i< n; i++){
            pq.offer(new int[]{0, i, matrix[0][i]});
        }
        
        for(int i=0; i<k-1; i++){
            int[] t = pq.poll();
            if(t[0] == n-1) continue;
            pq.offer(new int[]{t[0]+1, t[1], matrix[t[0]+1][t[1]]});
        }
        
        return pq.poll()[2];
    }
}
public class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int m = matrix.length, n = matrix[0].length;
        int lo = matrix[0][0],  hi = matrix[m-1][n-1];
        while(lo < hi){
            int mid = lo + (hi-lo)/2;
            int count = 0, j = n -1;
            for(int i=0; i<m; i++){
                while(j >=0 && matrix[i][j] > mid) j--;
                // count those <= mid
                count += j+1;
            }
            // if count < k, the number is smaller
            if(count < k) lo = mid+1;
            else hi = mid;
        }
        return lo;
    }

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。