378. Kth Smallest Element in a Sorted Matrix

Given anxnmatrix 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.

Analysis:

minHeap, push all first column element into minHeap, everytime poll() one from minheap, add the next element from that row unless out of bound. In minheap, we need to add in Cell object, which holds (x,y) and its value, so when we poll it out, we know the next element in that row is just (x, y+1)

Code:

public class Solution {
    public int kthSmallest(int[][] matrix, int k) {

        PriorityQueue<Cell> minheap = new PriorityQueue<Cell>(matrix.length, new Comparator<Cell>(){
            @Override
            public int compare(Cell a, Cell b)
            {
                if(a.value == b.value)
                {
                    return 0;
                }
                else
                {
                    return a.value < b.value ? -1 : 1;
                }
            }
        });

        for(int i=0; i<matrix.length; i++){
            minheap.offer(new Cell(i, 0, matrix[i][0]));
        }

        for(int i=0; i<k-1; i++)
        {
            Cell cur = minheap.poll();
            if(cur.y+1 < matrix[0].length)
            {
                minheap.offer(new Cell(cur.x, cur.y+1, matrix[cur.x][cur.y+1]));
            }
        }
        return minheap.peek().value;
    }

    public class Cell{
        public int x = 0;
        public int y = 0;
        public int value = 0;
        public Cell(int xx, int yy, int v)
        {
            x = xx;
            y = yy;
            value = v;
        }
    }
}

results matching ""

    No results matching ""