Kth smallest number in Sorted Matrix

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.