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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
/** | |
* @param matrix: a matrix of integers | |
* @param k: an integer | |
* @return: the kth smallest number in the matrix | |
*/ | |
public int kthSmallest(int[][] matrix, int k) { | |
// write your code here | |
// handle extreme cases | |
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) { | |
return -1; | |
} | |
if (k == 0) { | |
return -1; | |
} | |
int n = matrix.length; | |
int m = matrix[0].length; | |
PriorityQueue<Cell> heap = new PriorityQueue<Cell>(n, cellComparator); | |
for (int i = 0; i < n; i++) { | |
heap.add(new Cell(matrix[i][0], i, 0)); | |
} | |
for (int i = k; i > 1; i--) { | |
Cell poll = heap.poll(); | |
if (poll.y < m - 1) { | |
heap.add(new Cell(matrix[poll.x][poll.y + 1], poll.x, poll.y + 1)); | |
} | |
} | |
if (heap.isEmpty()) { | |
return -1; | |
} else { | |
return heap.poll().val; | |
} | |
} | |
Comparator<Cell> cellComparator = new Comparator<Cell>() { | |
public int compare(Cell o1, Cell o2) { | |
return o1.val - o2.val; | |
} | |
}; | |
private class Cell { | |
int val; | |
int x; | |
int y; | |
public Cell() { | |
} | |
public Cell(int val, int x, int y) { | |
this.val = val; | |
this.x = x; | |
this.y = y; | |
} | |
} | |
} |
No comments:
Post a Comment