L378. Kth Smallest Element in a Sorted Matrix

Problem:

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.

Solution:

  • minHeap, top kth is the result

public int kthSmallest(int[][] matrix, int k){
    int row = matrix.length;
    int col = matrix[0].length;
    PriorityQueue<int[]> minHeap = new PriorityQueue<>((a,b) -> matrix[a[0]][a[1]] - matrix[b[0]][b[1]]);
    for(int i = 0; i < col; i++){
        int[] cur = {0,i};
        minHeap.offer(cur);
    }
    for(int i = 0; i < k; i ++){
        int[] cur = minHeap.poll();
        if(cur[0] == row - 1){
            continue;
        }
        minHeap.offer(new int[]{cur[0]+1, cur[1]});
    }
    int[] cur = minHeap.poll();
    return matrix[cur[0],cur[1]];
}

Last updated

Was this helpful?