Find the kth smallest number in at row and column sorted matrix.
Example
Given k = and 4
a matrix:
[ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9],]
Return5.
Analysis:
Although the matrix is horizontally and vertically sorted, there are no rule to find the next smallest number. In this solution, we'll put the numbers in the first row to a heap, and remove the smallest one and add a new number who Se position is right under the removed one.
Note:when requesting to find the kth largest/smallest number, you should consider heap sort.
1 Public classSolution {2 /**3 * @param matrix:a matrix of integers4 * @param k:an integer5 * @return: the kth smallest number in the matrix6 */7 Public intKthsmallest (int[] Matrix,intk) {8 if(Matrix = =NULL|| Matrix.length = =0|| matrix[0].length = =0) {9 return 0;Ten } One if(k > Matrix.length * matrix[0].length) { A return 0; - } - returnVertical (matrix, k); the } - - Private intVerticalint[] Matrix,intk) { -queue<point> heap =NewPriorityqueue<point> (k,NewComparator<point>() { + Public intCompare (Point-left, point-right) { - returnLeft.val-Right.val; + } A }); at for(inti =0; I < Math.min (matrix[0].length, K); i++) { -Heap.offer (NewPoint (0, I, matrix[0][i])); - } - for(inti =1; I <= K-1; i++) { -Point Curr =Heap.poll (); - if(Curr.row +1<matrix.length) { inHeap.offer (NewPoint (Curr.row +1, Curr.col, Matrix[curr.row +1][curr.col])); - } to } + returnHeap.peek (). val; - } the } * $ classPoint {Panax Notoginseng Public intRow, col, Val; - PublicPoint (intRowintColintval) { the This. Row =Row; + This. Col =Col; A This. val =Val; the } +}
Kth smallest number in Sorted Matrix