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.
public class Solution {
    public int kthSmallest(int[][] matrix, int k) {

        class Pair{
            int x;
            int y;
            Pair(int a, int b){
                x = a;
                y = b;
            }
        };

        Comparator<Pair> comp = new Comparator<Pair>(){
            @Override
            public int compare(Pair p1, Pair p2){
                return matrix[p1.x][p1.y] - matrix[p2.x][p2.y];
            }
        };

        PriorityQueue<Pair> pq = new PriorityQueue<>(matrix[0].length,comp);

        for(int i=0; i< matrix[0].length; i++){
            pq.add(new Pair(0, i));
        }
        Pair p = null;
        while(k > 1){
            p = pq.poll();
            if(p.x + 1 < matrix.length)
                pq.add(new Pair(p.x+1, p.y));
            k--;
        }

        p = pq.poll();
        return matrix[p.x][p.y];

    }
}

results matching ""

    No results matching ""