Kth Smallest Element in a Sorted Matrix

lc 378 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.
class Solution {
    class Point{
        int x;
        int y;
        int val;
        public Point(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }
    }

    class PointComparator implements Comparator<Point> {
        public int compare(Point a, Point b) {
            return a.val - b.val;
        }
    }

    public int kthSmallest(int[][] matrix, int k) {
        int[] dx = new int[] {0, 1};
        int[] dy = new int[] {1, 0};
        boolean[][] hasAdded = new boolean[matrix.length][matrix[0].length];

        PriorityQueue<Point> queue = new PriorityQueue<Point>(k, new PointComparator());
        queue.offer(new Point(0, 0, matrix[0][0]));
        hasAdded[0][0] = true;

        while(k > 1) {
            Point cur = queue.poll();
            k--;
            for (int j = 0 ; j < 2; j++) {
                int xNext = cur.x + dx[j];
                int yNext = cur.y + dy[j];
                if (xNext < matrix.length && yNext < matrix[0].length && !hasAdded[xNext][yNext]) {

                    queue.offer(new Point(xNext, yNext, matrix[xNext][yNext]));
                    hasAdded[xNext][yNext] = true;
                }
            }
        }
        return queue.poll().val;
    }
}

results matching ""

    No results matching ""