public int kthSmallest(int[][] matrix, int k) { // write your code here if(matrix.length == 0) { return -1; } PriorityQueue<Element> heap = new PriorityQueue<>(); int row = matrix.length; for(int j = 0; j < row; j++) { heap.add(new Element(j, 0, matrix[j][0])); } int count = 1; while(count < k) { if(heap.size() == 0) { break; } Element top = heap.poll(); count++; if(top.col == matrix[0].length-1) { continue; } heap.add(new Element(top.row, top.col+1, matrix[top.row][top.col+1])); } if(count < k) { return -1; } return heap.poll().val; }
class Element implements Comparable<Element>{ public int val; public int col; public int row; public Element(int row, int col, int val) { this.row = row; this.col = col; this.val = val; } @Override public int compareTo(Element o) { // TODO Auto-generated method stub return this.val > o.val ? 1 : this.val < o.val ? -1 : 0; } }