[Lintcode] Kth Smallest Number in Sorted Matrix

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.