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 }
时间: 2024-10-12 01:05:53