378. Kth Smallest Element in a Sorted Matrix

Description

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.

**Note: **
You may assume k is always valid, 1 ≤ k ≤ n2.

Solution

MinHeap, time O(max(n, k) * log k), space O(n)

Here is the step of my solution:

  • Build a minHeap of elements from the first row.
  • Do the following operations k-1 times :
    • Every time when you poll out the root(Top Element in Heap), you need to know the row number and column number of that element(so we can create a tuple class here), replace that root with the next element from the same column.

After you finish this problem, thinks more :

  • For this question, you can also build a min Heap from the first column, and do the similar operations as above.(Replace the root with the next element from the same row)
class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        PriorityQueue queue 
            = new PriorityQueue<>((a, b) 
                    -> Integer.compare(get(matrix, a), get(matrix, b)));
        // offer first k elements in first column
        for (int i = 0; i < Math.min(n, k); ++i) {
            queue.offer(new int[] {i, 0});
        }
        
        while (--k > 0) {
            int[] curr = queue.poll();
            if (curr[1] + 1 < n) {
                curr[1]++;
                queue.offer(curr);
            }
        }
        
        return get(matrix, queue.peek());
    }
    
    private int get(int[][] matrix, int[] pos) {
        return matrix[pos[0]][pos[1]];
    }
}

你可能感兴趣的:(378. Kth Smallest Element in a Sorted Matrix)