LF.26.Kth Smallest Number In Sorted Matrix

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LF.26.Kth Smallest Number In Sorted Matrix相关的知识,希望对你有一定的参考价值。

Given a matrix of size N x M. For each row the elements are sorted in ascending order, and for each column the elements are also sorted in ascending order. Find the Kth smallest number in it.

Assumptions

the matrix is not null, N > 0 and M > 0
K > 0 and K <= N * M
Examples

{ {1, 3, 5, 7},

{2, 4, 8, 9},

{3, 5, 11, 15},

{6, 8, 13, 18} }

the 5th smallest number is 4
the 8th smallest number is 6


Assumptions

the matrix is not null, N > 0 and M > 0
K > 0 and K <= N * M

 

 

 1 class Solution {
 2     public int kthSmallest(int[][] matrix, int k) {
 3         int rows = matrix.length ;
 4         int cols = matrix[0].length ;
 5         Queue<Cell> minHeap = new PriorityQueue<Cell>(k, new CellComparator());
 6         //marker for visited: same rol and col
 7         boolean[][] visited = new boolean[rows][cols] ;
 8         //expand
 9         minHeap.offer(new Cell(0,0,matrix[0][0])) ;
10         visited[0][0] = true ;
11         /*pop k-1 then whats left is the kth smallest: 
12         因为行,列 都是单调递增,所以下一个最小的值,肯定在当前点的 左边,或者右边。 
13         你不需要考虑加 哪个, pq 又可以帮你做到抛最小的,
14         所以要严格利用这个性质 做 kth 最小,最大的题。
15         */
16         for (int i = 0; i < k-1 ; i++ ) {
17             Cell curr = minHeap.poll();
18             //when dealing with index +1 for array, always checks boundary
19             if (curr.row+1<rows && !visited[curr.row+1][curr.col]) {
20                 minHeap.offer(new Cell(curr.row+1, curr.col, matrix[curr.row+1][curr.col]));
21                 visited[curr.row+1][curr.col] = true ;
22             }
23             if (curr.col+1<cols && !visited[curr.row][curr.col+1]) {
24                 minHeap.offer(new Cell(curr.row, curr.col+1, matrix[curr.row][curr.col+1]));
25                 visited[curr.row][curr.col+1] = true ;
26             }
27         }
28         //已经抛出去 k-1 那剩下的 peek 一下就是 第k 个最小的
29         return minHeap.peek().val;
30     }
31 }
32 // PriorityminHeap for custom class requires implements Comparator<T>
33 class Cell{
34     public int row ;
35     public int col ;
36     public int val;
37     public Cell (int row, int col, int val){
38         this.row = row ;
39         this.col = col ;
40         this.val = val ;
41     }
42 
43 }
44 class CellComparator implements Comparator<Cell>{
45     @Override
46     public int compare(Cell c1, Cell c2){
47         return c1.val - c2.val ;
48     }
49 }

 

以上是关于LF.26.Kth Smallest Number In Sorted Matrix的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1038. Recover the Smallest Number

1038 Recover the Smallest Number (30 分)

[LeetCode] 2336. Smallest Number in Infinite Set

PAT1038. Recover the Smallest Number

PAT 1038 Recover the Smallest Number[dp][难]

Lintcode401 Kth Smallest Number in Sorted Matrix solution 题解