378. 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.
分析:
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 class Solution { 2 public int kthSmallest(int[][] matrix, int k) { 3 // be aware, the matrix may not be full matrix. 4 if (matrix == null || matrix.length == 0 || matrix[0].length == 0 || k > matrix.length * matrix[0].length) { 5 throw new IllegalArgumentException("Invalid input"); 6 } 7 return helper(matrix, k); 8 } 9 10 private int helper(int[][] matrix, int k) { 11 Queue<Point> heap = new PriorityQueue<>(k, (p1, p2) -> matrix[p1.row][p1.col] - matrix[p2.row][p2.col]); 12 for (int i = 0; i < Math.min(matrix[0].length, k); i++) { 13 heap.offer(new Point(0, i)); 14 } 15 for (int i = 1; i <= k -1; i++) { 16 Point curr = heap.poll(); 17 if (curr.row + 1 < matrix.length) { 18 heap.offer(new Point(curr.row + 1, curr.col)); 19 } 20 } 21 return matrix[heap.peek().row][heap.peek().col]; 22 } 23 } 24 25 class Point { 26 public int row, col; 27 public Point(int row, int col) { 28 this.row = row; 29 this.col = col; 30 } 31 }