码迷,mamicode.com
首页 > 其他好文 > 详细

Kth Smallest Number in Sorted Matrix

时间:2016-07-14 07:10:27      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

Find the kth smallest number in at row and column sorted matrix.

Example

Given k = 4 and a matrix:

[
  [1 ,5 ,7],
  [3 ,7 ,8],
  [4 ,8 ,9],
]

return 5.

分析:

Although the matrix is horizontally and vertically sorted, there is no rule to find the next smallest number. In this solution, we will put the numbers in the first row to a heap, and remove the smallest one and add a new number whose position is right under the removed one. 

Note: when requesting to find the kth largest/smallest number, you should consider heap sort.

 1 public class Solution {
 2     /**
 3      * @param matrix: a matrix of integers
 4      * @param k: an integer
 5      * @return: the kth smallest number in the matrix
 6      */
 7     public int kthSmallest(int[][] matrix, int k) {
 8         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
 9             return 0;
10         }
11         if (k > matrix.length * matrix[0].length) {
12             return 0;
13         }
14         return vertical(matrix, k);
15     }
16     
17     private int vertical(int[][] matrix, int k) {
18         Queue<Point> heap = new PriorityQueue<Point>(k, new Comparator<Point>() {
19             public int compare(Point left, Point right) {
20                 return left.val - right.val;
21             }
22         });
23         for (int i = 0; i < Math.min(matrix[0].length, k); i++) {
24             heap.offer(new Point(0, i, matrix[0][i]));
25         }
26         for (int i = 1; i <= k -1; i++) {
27             Point curr = heap.poll();
28             if (curr.row + 1 < matrix.length) {
29                 heap.offer(new Point(curr.row + 1, curr.col, matrix[curr.row + 1][curr.col]));
30             }
31         }
32         return heap.peek().val;
33     }
34 }
35 
36 class Point {
37         public int row, col, val;
38         public Point(int row, int col, int val) {
39             this.row = row;
40             this.col = col;
41             this.val = val;
42         }
43     } 

 

 

Kth Smallest Number in Sorted Matrix

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5668854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!