首页 > 其他 > 详细

378. Kth Smallest Element in a Sorted Matrix

时间:2017-10-24 15:24:55      阅读:96      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/wzj4858/p/7723700.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!