標籤:
Kth Smallest Number in Sorted Matrix
Find the kth smallest number in at row and column sorted matrix.
Have you met this question in a real interview?
YesExample
Given k = 4 and a matrix:
[ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9],]
return 5
Challenge
O(k log n), n is the maximal number in width and height.
實際上是和醜數問題類似的一個問題,也是使用一個優先隊列
1 import java.util.*; 2 3 class Node{ 4 public int row; 5 public int col; 6 public int value; 7 public Node(int row,int col, int value){ 8 this.row = row; 9 this.col = col;10 this.value = value;11 }12 }13 public class Solution {14 /**15 * @param matrix: a matrix of integers16 * @param k: an integer17 * @return: the kth smallest number in the matrix18 */19 private void set(int row,int col,boolean [][] visited, int [][]matrix, PriorityQueue<Node> heap){20 int m = visited.length;21 int n = visited[0].length;22 if(row<0||row>=m||col<0||col>=n||visited[row][col]) return;23 heap.offer(new Node(row,col,matrix[row][col]));24 visited[row][col]=true;25 }26 public int kthSmallest(int[][] matrix, int k) {27 // write your code here28 Comparator<Node> mycompare = new Comparator<Node>(){29 public int compare(Node n1,Node n2){30 return n1.value-n2.value;31 }32 };33 boolean [][] visited = new boolean[matrix.length][matrix[0].length];34 PriorityQueue<Node> heap = new PriorityQueue<Node>(k,mycompare);35 heap.offer(new Node(0,0,matrix[0][0]));36 int selected = 0;37 visited[0][0]=true;38 for(int i=0;i<k;i++){39 Node node = heap.poll();40 selected = node.value;41 int row = node.row;42 int col = node.col;43 44 set(row+1,col,visited,matrix,heap);//down45 set(row,col+1,visited,matrix,heap);//right46 }47 return selected;48 }49 }
[Lintcode] Kth Smallest Number in Sorted Matrix