Lintcode: Kth Smallest Number in Sorted Matrix

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

Challenge

KLog(Min(M,N,K))时间复杂度 K是因为要Poll K次并且同时insert K次,Min(M,N,K)是堆的size,insert的时间是Log(MIN(M,N,K))

思路就是维护一个最小堆,先把第一行,或第一列(本题做法是第一列,之后默认第一列)加入堆中,poll K次,每poll一次之后要把poll的元素的下一个元素加入堆中,本题就是poll的元素的下一列元素。最后一次poll的元素即为所求。因为需要知道每个poll的元素的位置,所以写了个Point Class

 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     
 8         // write your code here
 9         public class Point {
10             public int x, y, val;
11             public Point(int x, int y, int val) {
12                 this.x = x;
13                 this.y = y;
14                 this.val = val;
15             }
16         } 
17         
18         Comparator<Point> comp = new Comparator<Point>() {
19             public int compare(Point left, Point right) {
20                 return left.val - right.val;
21             }
22         };
23         
24         public int kthSmallest(int[][] matrix, int k) {
25             if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
26                 return 0;
27             }
28             if (k > matrix.length * matrix[0].length) {
29                 return 0;
30             }
31             return horizontal(matrix, k);
32         }
33         
34         private int horizontal(int[][] matrix, int k) {
35             Queue<Point> heap = new PriorityQueue<Point>(k, comp);
36             for (int i = 0; i < Math.min(matrix.length, k); i++) {
37                 heap.offer(new Point(i, 0, matrix[i][0]));
38             }
39             for (int i = 0; i < k - 1; i++) {
40                 Point curr = heap.poll();
41                 if (curr.y + 1 < matrix[0].length) {
42                     heap.offer(new Point(curr.x, curr.y + 1, matrix[curr.x][curr.y + 1]));
43                 }
44             }
45             return heap.peek().val;
46         }
47             
48         
49 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/5137039.html