标签:matrix col order logs pre priority 第k小 asc amp
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
题目含义:给定一个升序的矩阵,找到第k小的元素
方法一:使用优先级队列
1 public int kthSmallest(int[][] matrix, int k) { 2 PriorityQueue<Integer> pq = new PriorityQueue<>(); 3 if (matrix.length == 0) return Integer.MAX_VALUE; 4 for (int i = 0; i < matrix.length; i++) { 5 for (int j = 0; j < matrix[0].length; j++) { 6 pq.add(matrix[i][j]); 7 } 8 } 9 int i = 0; 10 while (i < k - 1) { 11 if (!pq.isEmpty()) pq.poll(); 12 i++; 13 } 14 if (!pq.isEmpty()) return pq.poll(); 15 return Integer.MAX_VALUE; 16 }
378. Kth Smallest Element in a Sorted Matrix
标签:matrix col order logs pre priority 第k小 asc amp
原文地址:http://www.cnblogs.com/wzj4858/p/7723700.html