My code:
public class Solution {
public int kthSmallest(int[][] matrix, int k) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return -1;
}
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return -1 * (i1.compareTo(i2));
}
});
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (pq.size() < k) {
pq.offer(matrix[i][j]);
}
else {
if (matrix[i][j] < pq.peek()) {
pq.poll();
pq.offer(matrix[i][j]);
}
}
}
}
return pq.peek();
}
}
這道題目直接拿 map-heap 來解了忘朝。感覺效率也并不是很高。
可以再優(yōu)化赁濒。
如果某一列的某個數(shù)字被彈出后,那么這一列剩下的數(shù)字都不可能進(jìn)入這個堆孟害,沒必要再試了拒炎。
My code:
public class Solution {
private class Tuple {
int row;
int col;
int val;
Tuple(int row, int col, int val) {
this.row = row;
this.col = col;
this.val = val;
}
}
public int kthSmallest(int[][] matrix, int k) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return -1;
}
PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>(k, new Comparator<Tuple>() {
public int compare(Tuple i1, Tuple i2) {
return -1 * (i1.val - i2.val);
}
});
boolean[] col = new boolean[matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (col[j]) {
continue;
}
if (pq.size() < k) {
Tuple t = new Tuple(i, j, matrix[i][j]);
pq.offer(t);
}
else {
if (matrix[i][j] < pq.peek().val) {
Tuple t = pq.poll();
pq.offer(new Tuple(i, j, matrix[i][j]));
col[t.col] = true;
}
}
}
}
return pq.peek().val;
}
}
先這樣吧。
Anyway, Good luck, Richardo! -- 09/15/2016