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<int[]> 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]];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容