F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[Lintcode] Kth Smallest Number in Sorted Matrix

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? 

Yes
Example

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 integers
16      * @param k: an integer
17      * @return: the kth smallest number in the matrix
18      */
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 here
28         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);//down
45             set(row,col+1,visited,matrix,heap);//right
46         }
47         return selected;
48     }
49 }

 

posted on 2015-09-03 20:41  F_G  阅读(956)  评论(0编辑  收藏  举报