public int kthSmallest(int[][] matrix, int k) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
throw new IllegalArgumentException("");
}
PriorityQueue<Point> queue = new PriorityQueue<>(11, new Comparator<Point>(){
@Override
public int compare(Point a, Point b){
return a.val - b.val;
}
});
int row = matrix.length;
int col = matrix[0].length;
int n = row*col;
queue.offer(new Point(0,0,matrix[0][0]));
while(--k>0){
Point p = queue.peek();
queue.poll();
if (p.i == 0 && p.j+1 < col) {
queue.offer(new Point(p.i, p.j+1, matrix[p.i][p.j+1]));
}
if (p.i + 1 < row) {
queue.offer(new Point(p.i+1, p.j, matrix[p.i+1][p.j]));
}
}
return queue.peek().val;
}
class Point{
int val = 0;
int i = 0;
int j = 0;
public Point(int i, int j, int val) {
this.val = val;
this.i = i;
this.j = j;
}
}
public int kthSmallest(int[][] matrix, int k) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
throw new IllegalArgumentException("");
}
PriorityQueue<Integer> queue = new PriorityQueue<>(11, new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b){
return a - b;
}
});
for (int[] array: matrix) {
for (int i: array) {
queue.offer(i);
}
}
for (int i = 1; i < k; i++) {
queue.poll();
}
return queue.poll();
}
Kth Smallest Element in a Sorted Matrix
最新推荐文章于 2020-07-19 10:21:13 发布